#💻┃code-beginner
1 messages · Page 150 of 1
I prefer the if if if if if approach myself
i mean i could make a function in the Enemy class itself but it defeats the whole purpose of the AnimationTriggerEvent
can probably just do that in script if you can't get it to work
that's the only thing that really sticks out in the video, otherwise basic trigger methods
thanks anyways, guess i have to do just that
some more questions:
what's the difference between an object and a component
how do you get references to other components on the same gameobject
what is a transform
I think instead of memorizing what each word means, try to understand what an entire block of code does. For me when im reading code I like to try to translate it almost into words so i can understand what its doing better. All you need to do is get the basics of c# and the rest comes with study and practice, once youve gotten to a confident level you can now code in almost any programming language just from your knowledge of c# isnt that cool :D
experts do if if else if if if else if… and turn off auto-indentation for a real challenge
hey, if I got the screen space, I'm going to use it all
if
else if
if
else if
else
if
if
if
else if
“Mr Interviewer, if you can’t read this code, your programming skills must just be insufficient.”
if can follow nothing, else can follow else if or if, else if must follow if
task: write a backtracking function to generate all possibles control flow
hint: you will need a stack
I have a sort of architecture question. I have a gun which you can upgrade through UI, upgrades can be homing bullets, bullets that curve, bigger bullets etc. You are supposed to combine different upgrades how you like. At the moment i have boolean flags that are set for each upgrade, so in the gun class for example i just check for flags
If (homingBullets){//do smth}
If(bigBullets) {//do smth}
Now there are going to be quite alot of upgrades, is this the way to approach it?
state machine ``` public enum State
{
Idle,
Moving,
Running,
Attacking,
Pause
}
private State currentState = State.Idle;```
So the return is being called when attack and wont leave and the animation is still showing its prevouis animation. i read about somthing called Rebind(); Could that fix the issue?
Hey guys, what would be the most straightforward way of checking if two objects are colliding?
OnCollisionEnter()
Which is automaticly run when something with a collider enters its colliding field?
I don't quite understand how that would help me, A state machine swaps between states, in my scenario i would then need multiple states to coexist as you combine upgrades
someone asked this question a few days ago
do you mean like in half or by 50% opacity lol
#3DProblems
prob want to create a shader and lerp between the alphas
im not 100% sure but thats what i would google
Set the alpha to 0.5 and make sure you are using a transparent shader
anyone know why im getting these errors
https://pastebin.com/hLZsjV54
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Yeah, you're trying to get something from a collection (array or list) with an index that is outside the range of the collection.
Look at PlayerControllerNew.SamuraiAttack () (at Assets/PlayerControllerNew.cs:222)
thats this ```csharp
animator.runtimeAnimatorController = SamuraiCombo[ComboCounter].animatorOV;
im confused because it works fine but after i attack smth enough times it stops resetting it and goes outside the range
public void SamuraiAttack()
{
if (Time.time - lastComboEnd > 0.5f && ComboCounter <= SamuraiCombo.Count)
{
CancelInvoke("EndCombo");
if (Time.time - lastClickTime >= 0.333f)
{
Debug.Log(ComboCounter);
animator.runtimeAnimatorController = SamuraiCombo[ComboCounter].animatorOV;
soundEffects.clip = SamuraiAudio[ComboCounter];
soundEffects.Play();
animator.Play("Attack", 0, 0);
Damage = SamuraiCombo[ComboCounter].attackDamage;
ComboCounter++;
lastClickTime = Time.time;
DoAttack();
Moves moves = gameObject.GetComponent<Moves>();
moves.PerformPunch();
if (ComboCounter >= SamuraiCombo.Count)
{
ComboCounter = 0;
}
}
}
}
thats the whole thing so im not sure how it is reaching more then is in the array/list
ComboCounter <= SamuraiCombo.Count
wouldnt that reset it each time you attack
Index of element is starting from 0 and List Count from 1
i know
but how about .Count is 0
So it should be just <
it’s worth mentioning that SamuraiAttack should have very limitted connection to combo count
or at initial ComboCounter = SamuraiCombo.Count
there should be a different object entirely that manages combo count, and tries adding to it.
then your
if (ComboCounter >= SamuraiCombo.Count)
{
ComboCounter = 0;
}
```is useless
this function also should not be directly messing with the animation controller. this function is just handling way too many different jobs
it works most of the time it just randomly will break
Before you go in deep trying to fix it, try logging ComboCounter and the size of SamuraiCombo right before the line with the error. See what the values are right before the error in the console and find out which one is going to a value you don't expect.
what does this mean
MissingComponentException while executing 'performed' callbacks of 'Player/Attack[/Mouse/leftButton,/XInputControllerWindows/buttonWest]'
UnityEngine.InputSystem.LowLevel.NativeInputRuntime/<>c__DisplayClass7_0:<set_onUpdate>b__0 (UnityEngineInternal.Input.NativeInputUpdateType,UnityEngineInternal.Input.NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate (UnityEngineInternal.Input.NativeInputUpdateType,intptr)
That's just a biproduct of your actual issue
Fix the real issue, and it will go away
An error occurred in whatever callback your "Button West" is mapped to. Which I'm pretty sure is the one we're already working on
I believe that, when an exception is thrown in an action callback, you get two errors in the console
One is the original exception, and another is just an error logged by the input system
why is my default layer above background layer when i put my characters layer above the background?
(you can log an error message whenever you want; they're not just caused by exceptions)
did that found that what happens is every time normally it gets to 4 then resets so you never get to 5 which is the size of samuraicombo but for some weird reason after i do like 3 full combos on a enemy it just goes to 5 and doesnt reset
normally it would do this
These logs are useless without context. Which one is the combo counter and which one is the length
combo counter is the first one length is the second one
which is the first one.....
Show the out of range exception error?
so for the second image combocounter is 3 4 0 1 2 and length is 5 5 5 5
Logging both at the same time would help.
Change the logs to include which it is, or better yet put them into one line with both values, both labeled
Debug.Log($"Counter: {counter} / Length: {comboLength}");
At this point I'm assuming it's a missing component exception
(i made these variable names up)
That's a completely new error that has never been mentioned so far but we'll get to that next
Was there a confirmed initial error? 
Yes, an out of range exception
this is what normally happens
then this is what happens when it breaks
there is no animator
So the counter should be one less than the count since you're counting from zero.
Okay, so your counter is too high. You have 5 things in the list but your combo counter is trying to get the sixth element
So either you're incrementing it elsewhere or the reset isn't occurring.
i think the no animator error causes your if(counter>=count) statement dont execute and then you get many index out bound s
Likely so. Fix the errors from the top to the bottom.
then the index out of bound is ofc interrupt your program everytime hence the if statement are not executed at all
Else you may be attempting to fix false positives.
yep it was the animator error thanks
Always solve errors top to bottom
how do i check if the object has a component before i try to get it
When an error occurs, the code stops
Guys I need a help that how to do that wheels will rotate but without wheel colliders pls
public void OnCancelButtonPressed()
{
if(abandonMissionModalOpened)
{
Debug.Log("pre null check");
if(abandonMissionModal != null)
{
Debug.Log("turning off modal window");
abandonMissionModal.TurnCanvasGroupOn(false);
if (isInGame)
{
PauseManager.Instance.UnpauseGame();
}
return;
}
}
Debug.Log("turning off options");
}
I have an issue, where the last Debug.Log is still being print, despite the return above, and the logs above prints aswell and im not sure what is going on xd the functions is being called only once, after a keyboard button(or gamepad button) press
Can you show an image of the console log?
sorry nevermind, fixed it
i subsribed to the event twice by a mistake
(well, didint unsubscribe on scene change)
then subbed aggain
is there any way to make an exception on control child size in a vertical layout group, I have a layout with a text and a button under it and when the size of the text adjust the button shrinks, if this makes sense
the button shrinks b/c the area it can be shrinks..
it just scales to fit within
no clue how to fix it tho, i suck at layout groups.. they're just trial and error for me..
try #📲┃ui-ux
The button needs a layout group.
You currently have this:
- Root <-- VerticalLayoutGroup
- Button
- Text
- Button
^ that makes sense.. it should be within it yea, like DIV's in css
Attach a VerticalLayoutGroup to Button and make it control its child's size
If an object has no layout group on it, then it won't be aware of the size requested by its children
so it won't ask for any space
how do u indent the bullets like that?
You should read the Auto Layout section of the UI docs https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/UIAutoLayout.html
just adding spaces before each bullet (or dash, in my case)
- foo
- bar
- baz
ya that doesnt work
yeap 🙂
im thankful discord added that feature
helps with visualizing the hiearchy
You can check how much space a UI object is asking for in the bottom of the inspector. You may need to switch modes.
e.g. I need to switch this to "Layout Properties" to see it
if you have further questions about this, ask 'em in #📲┃ui-ux
oh, Raspu did post over there! missed that.
fixed it
i crated a lay out group for the text and added it into the original layout group that doesnt adjust the size but the other one does
!code void EatFood()
{
// Check if there's food nearby
Collider[] colliders = Physics.OverlapSphere(transform.position, 2f);
foreach (Collider col in colliders)
{
if (col.CompareTag("Food"))
{
// Get the Food script and eat the food
Food food = col.GetComponent<Food>();
if (food != null)
{
currentHunger += food.nutritionalValue;
// Remove the food from the scene
Destroy(col.gameObject);
appleEatSound.Play();
Debug.Log("Player Ate Something");
}
}
}
} when im trying to eat the object if theres 1 object in the scene that im trying consume it works fine but if theres 2 of the same object it consumes both if im trying to consume only one of them how do i fix this
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
break; after eating one
how do i implement that
That is the implementation
Literally just add break; at the end
its that simple?? dang
break; breaks out of the current loop or switch statement
bro it actually worked wtf thank u'
There's also yield break;
It so often is wtf. With a couple of omg's thrown in there. "Oh, no my code actually works just fine, but I forgot to add a critical '!' to it", "oh wait, why am I dividing that?", etc.
Or the hilarious "argh! I was editing the wrong file all along!"
What alpha?
Of your material
where?
On the color
where is transparent shader?
Change it from opaque to transparent
Ok, thanks, now it works
@frank flare this isn't a coding question. In the future, stay in one place.
ok
I still cant get my attack to work when my player is being instatiated
my state is attack yet the animator is showing idle and i can no longer move as it thinks its in attack state. This only breaks when ithe player is instatiated.#
attack comes from any state
You should be able to open the parameters tab and see the values change
Are you sure you're referencing the correct Animator
Well there is only one player on the scene and i have clicked that game object and moved around the scene and i can see it swapping. Its only on attack it breaks.
this is after attack is pressed
So those are all triggers?
yes
Show the transition from attack to idle
I see nothing in here ever setting the Attack trigger
there is no trigger on attack to idle. i have a trigger at the end of the animation
The attack does not even play. just goes straight to idle yet this debug is always displaying
{
Debug.Log(playerState.CurrentState);
if (playerState.CurrentState == PlayerState.State.Attacking)
{
// Player is attacking, disable movement
return;
}```
its state is attack
Nowhere in any of the code you sent are you setting the Attack trigger in your animator
void OnAttackAnimationEnd()
{
playerState.ChangeState(PlayerState.State.Idle);
Debug.Log("no");
}
oh sorry wrong code
{
private Animator _animator;
private PlayerState playerState;
void Start()
{
_animator = GetComponent<Animator>();
playerState = GetComponent<PlayerState>();
}
private void Update()
{
if (Input.GetMouseButtonDown(1))
{
if (playerState.CurrentState != PlayerState.State.Attacking)
{
Attack();
}
}
}
void Attack()
{
playerState.ChangeState(PlayerState.State.Attacking);
_animator.SetTrigger("Attack");
}
// Animation event handler for the end of the attack animation
void OnAttackAnimationEnd()
{
playerState.ChangeState(PlayerState.State.Idle);
Debug.Log("no");
}
}```
here is attack
Okay, so, in the code you showed before, clicking causes the player to enter the Attacking state. In here, whenever you click, you perform the attack only if the player is not in the Attacking state
So depending on which one executes first, you will either attack first then enter the attacking state, or enter the state and that's it
but why would this work when my player is in the hierarchy and then break when its being instatiated
If you're gonna use a state pattern, you should have the states handle this stuff
i do
Because the order Update runs is basically random
public class PlayerState : MonoBehaviour
{
public enum State
{
Idle,
Moving,
Running,
Attacking,
Pause
}
private State currentState = State.Idle;
public State CurrentState
{
get { return currentState; }
}
public void ChangeState(State newState)
{
currentState = newState;
}
}```
lol, first time ive encountered this issue.. seems navmesh agents can get stuck
These states don't do anything
the yellow one is just picking a random location, and the blue one is set when the ground is clicked.
have you tried shifting the priority?
nah, hadn't thought of that.. i was thinking id have to create a timer if it hasnt moved so far in so long then just set where it is as the target
need some swarm ai
but even that method doesn't seem like it would look all that pretty.
would take a bit of time b4 anything happens
So just so i understand. your saying my states are not working from the state class. and my attack class is unsetting a state that my player controller is setting?
oh I usually randomize or prioritize certain agents with priority, seems to help a little
ya, ill give that a try firstly
I am saying that you are specifically checking to make sure you are not in the Attacking state before playing the attack animation, and the same button press is also setting your state to Attacking. Meaning depending on which one gets the lower GUID you get different behavior
which is largely random
gl!
iirc lower is "higher priority" check docs to double check
thank you really appreciate your help and time.
lol ya its worded a bit odd to me..
yeah unity lol
so a lower value agent would be ignored by this one
but.. higher importance lol.. idk ill just test it
a lower priority agent will just push higher priority out the way lol
okie
yup that helps out alot
still need to tweak the NPC a bit
he gets a bit confused
nice! that can be a mechanic in itself
yeah starts wobbling
what is destination for yellow set to?
its randomized
if(masterOverride)
{
// Check if the agent has reached the destination
if(!navMeshAgent.pathPending && navMeshAgent.remainingDistance < 0.1f)
{
if(!waiting)
{
ChangeState(NPC_RX_State.IDLE);
// Start the wait timer
waitTimer = Random.Range(minWaitTime,maxWaitTime);
waiting = true;
}
else
{
// Continue waiting until the timer reaches zero
waitTimer -= Time.deltaTime;
if(waitTimer <= 0f)
{
// Set a new random destination after waiting
SetRandomDestination();
waiting = false;
}
}
}
else
{
ChangeState(NPC_RX_State.WANDERING);
waiting = false; // Reset the waiting flag if the NPC is not at the destination
}
}```
just some basic stuff to get it moving around
I think it tries to return to its original stopped position ?
yea it seems that way
as long as his destination is the same.
he tries to move back
the higher "importance" agent is in the way like an obstacle lol
so it tries to obstacle avoid and gets all weird
yea im wondering if i can maybe use the carve component
yea but that wouldnt work.. cuz he then wouldnt be on the nav
you would have to get real granular with it
like detect maybe if indeed was pushed then just set destination to be self instead
or something
ya, i think ill just hack it for now.. "Stray NPC" is supposed to represent like a wild animal
could just make it run away from the Unit if it gets close enough
animal sidekick do be wild
fight or flight.. (if unit is in personal space just freeze)
spazzing is ok lol
lol
but next up is interactions.. #💻┃code-beginner message
and this is supposed to be mobile.. so i keep struggling to keep my mechanics correct..
i realized if i keep one thing in my head it'll all work out..
(there is no hovering on mobile)
normally i would have it where u can hover the unit first.. and then a menu would pop up allowing u to click a button to navigate or a button to do something else...
but since i can't hover imma have to make a single click select it.. and then a click and hold would open said menu..
true, gotta work in that "held pressed" button
they should def add that onto cellphones 😄
like use magnetism or something (like capacitor type stuff) to detect if you are about to click
also direction, b/c now i have a toggle where he just faces the mouse position.. but that wont be possible on mobile..
im thinking of having it face the direction its moving unless u click and drag (then it would face that direction).. and tie that into my waypoint system..
soo... if a waypoint has a direction then the navmesh agent will slowly look towards that direction as its traversing to that position.. (slerping from the last waypoint direction to the new waypoint direction)
and then if theres no direction assigned to it, the unit would slerp towards its normal facing direction
Yeah I only use the agent rotation at certain points
otherwise it looks unnaturally stiff
Guess the first step would be to get a better waypoint system.. as right now its just a list of transforms..
should probably make a class or struct instead w/ multiple properties
also would store the results of Navmesh.SamplePosition
I had issues agents get weird when destination point isn't exactly on mesh
ya, that makes sense..
hello, i have a problem with my inventory system thingy which you can probably tell in the video, where once i drop an object i cant pick any up, if you would like to help im happy to send the script that i believe to be having problems
private void Update()
{
SeekWaypoints();
}
void SeekWaypoints()
{
if(waypoints.Count > 0)
{
navMeshAgent.SetDestination(waypoints[0].position);
if(navMeshAgent.remainingDistance <= navMeshAgent.stoppingDistance && !navMeshAgent.pathPending)
{
// Destination reached, remove the waypoint
GameObject curWay = waypoints[0].gameObject;
waypoints.RemoveAt(0);
Destroy(curWay);
// Check if there are more waypoints
if(waypoints.Count > 0)
{
// Set the next destination
navMeshAgent.SetDestination(waypoints[0].position);
}
else
{
// No more waypoints, stop the agent or perform other actions
navMeshAgent.ResetPath();
}
}
}
}``` heres the Unit script.
i just have a AddWaypoint() function where i pass in the Transform of the little blip i instantiate
then the agent handles the rest
I take that if we post a bug, we should use pastebin sites in our thread if there are 4 scripts involved?
i cranked up the rotation pretty high..
gives it a more natural feeling.. as if a waypoint is directly behind him.. he almost turns 180 as he starts moving..
idk if the raycast doesnt work or smth but when im clicking the button for it to consume the food its just not working https://gdl.space/elohequdis.cs
default settings are bad, lol.. unit will moonwalk half the trip b4 he gets fully turned around
yeah for sure
| yes |
that code is so annoying
Try to minimize what's needed because 4 scripts is a lot
use some debugs.. see if ur raycast and stuff is working
I see what you did there
ive tried its not for somereason
find out why
Video is nice but could be anything without the code
should i send the code?
i dont really know what to do
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
if u cant eleminate any of the code on your own just send links to all of it.. but it will less likely to be read and/or solved..
True! It is a GameManager, LivesManager, PlayerMovement, and PlayerLife script. It initially was two until I made a hearts manager system that required a LivesManager and GameManger, so there could be a potential way to merge the LivesManager and PlayerLife
but no one can help period, w/o it
I'd go a step further and say to never try and "simplify" code when asking for help
If you understood the code well enough to simplify it, you'd have solved the problem already
90% of my original bug was fixed with help from the Unity Forms, so the issue SHOULD be relatively small. Most of the mechanic works, just a small portion of it has issues
It is a heart management system, which I'll post a thread to
ahaha, well if they can solve it by simplifying than that's 4 less scripts you'd need to read into
most likely if ur code is half decent if ur leaving out any important scripts, they'll get asked for
BUT.. some of thse paste bin sites allow u to enter multiple scripts
hastebin i think
Nice code if you wrote it, but at this point it's a lot of places that could be the problem. This is where the visual studios debugger comes in handy where you can execute line by line or stick a bazillion breakpoints in the script
or do it ye ol' fashion way and stick a ton of debug logs and follow them
Well, good thing, only 3 of the scripts are needed. It does help fix at least one of my bugs with the player unable to move completely, now its just a smolllllllll bug
Hearts Management System Bug
thank you so much, this helped
Did you manage to look up how to attach the debugger?
It's really useful, especially when you've a bunch of logic you need to specifically dig through to point out the problem
Pretty useful such that here I'm just hovering over the values and getting it just then, and you can even do it during the editor runtime (such as attaching the debugger and creating new breakpoints)
the answer is prob 99% no, but i'll ask anyway
can I combine cases in a switch ?
like an or/and
case myEnum.xx || myEnum.yy
//stuff
On late enough versions of C# yes, try a case Thing.A or Thing.B
thats great
Or, the old way is to have two cases
case A:
case B:
// code
A will fall through B
renogareFont = Content.Load<SpriteFont>("\Font\Renogare-Regular.otf"); how do i make it so i dont have to copy the whole path?
a yes because there is no break and code underneath A ?
Correct!
well ty for answering
does anybody know why the Invoke method does not call the function?
for a moment I thought i would be impossielbe since i never seen a switch with combination in years
You destroy the object, everything running on it stops
only if the AI ship is destroyed, in this case the player ship gets destroyed
wait
What?
Like two lines in OnCollisionEnter you do Destroy(gameObject)
The issue is the Destroy call in Start
is there a way to create a new thread which exists once the original script is destroyed?
I hope you aren't trying multithreading in Unity
It doesn't go well
brother I just want the delayed function call to exist after I destroy the script
Simply call it on something you won't destroy
Call it on a GameObject that does not get destroyed . . .
Hey I don't know why but I get this error again
try reinstall .NET sdk
: ".NET sdk download"
in the "Controls" part of the code should i ask the position of the player as well as the game time so i dont have to do the "ballPosition += movementInput;" outside the function?
hey guys, how do i make a rigidbody character?
im pretty sure you just add rigidbody as an element of the character
well i've got a character controller player, but i want to use the properties of addforce and other stuff
and i can't really understand how to make the guy move with a rigid body
Character Controller and Rigidbody are incompatible
yep so im trying to switch to rigid body
If you switch to a Rigidbody make sure to remove the CC, you'll have to redo most of your movement code
yeah i know, but i don't know how to make him move with rigid body
that's the issue
cause i tried using the code from like a year or two ago
and apparently it's incompatible
There's AddForce, which produces smooth and more realistic movement, and MovePosition which is more crispy and reactive.
The Rigidbody API hasn't changed in a while, so I doubt the code is incompatible
Nothing with basic Rigidbody motion has changed in about 15 years
well i want it to be fun not realistic
which one should i use?
The answer can be deducted by reading my message one more time
But you can try both and see what feels the best
well alright...
I heard that using transform.Rotate is bad when dealing with rigidbodies in fixedupdate, what should I use instead?
where's the error?
objects = JsonUtility.FromJson<JsonObjects>(json: jsonFile.text);
This are the two scripts
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Deserialisation : MonoBehaviour
{
[SerializeField] public TextAsset jsonFile;
[SerializeField] public JsonObjects objects;
// Start is called before the first frame update
void Start()
{
objects = JsonUtility.FromJson<JsonObjects>(json: jsonFile.text);
Text sampleString = objects.Quote;
Debug.Log(sampleString);
}
// Update is called once per frame
void Update()
{
}
}
public struct JsonObjects
{
public Text Quote;
}
ArgumentException: JSON must represent an object type.
Your file doesn't contain valid JSON, it seems
how does move position work exactly
how did you save the data
{
"Quote": "echnique 29:\nThe exclusive smile\nIf you flash everybody the same smile, like a Confederate dollar, it loses value. When meeting groups of people, grace each with a distinct smile. Let your smiles grow out of the beauty Big Players find in each new face.\nIf one person in a group is more important to you than the others, reserve an especially big, flooding smile just for him or her.",
"Author": "alsdñgf",
"Source": "ewag"
}]```
into a JSON file
Well, your JSON has "Author" and "Source" that don't exist on your object
Moves towards the desired position, while respecting the physics interpolation settings and various other things
Docs : https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
And "Quote" is of type UnityEngine.UI.Text which is probably not right
i see, well thank you for your help i suppose
JsonUtility does not support arrays [...] as the root element. Use a more potent serializer like Newtonsoft.Json, then deserialize to a List<JsonObjects>
That class name is not really good, I'd call it Quote, simply
Because that's what it stores
i was following a YT tutorial
What tutorial
Converting JSON is very important when you want to use static data and use in your game.
I hope this video has helped you!
Don't forget to like the video and subscribe my channel :)
You can also follow me on twitter: @faithmorante
mines better, it uses generics 😏
Not sure if I can count this towards The Counter™️ since it looks like you're actually not copying the tutorial directly, which is somewhat of a rarity around these parts.
Still, Text is a UI GameObject and not what you want
You should make an instance of the object in code first and output it as JSON, then use that as a sample of what you should be doing
Quick question about OnDrawGizmoSelected().
I am generating handles in the above function, but its a bit complex and I do not want to run it every time. Is there a way to generate the handels, then only move them if the transform is updated? Like onvalidate with values of properies, but a onvalidate via transform.
The logic behind transform.has moved works while moving, but if I check against that, when it is not moving it doesn't draw them. Is it expected that these draw every time it loops or is there a better way to do this performance wise?
@smoky mauve https://youtu.be/Q0_xreJMldM?si=I79Ge2Zbcr7PztmH
Its expected for them to draw every frame it is a immediate mode style of gui
When doing the loop I am getting the hash value of objects and redrawing them, won't this cause issues if I try and do too many at once?
Not sure that helps, it's their JSON structure that's incompatible.
Also Directory.CreateDirectory() does nothing if the directories already exist, so you technically don't need to guard it with an if statement :)
Oh yeah ur right, appreciate it 🙂 I need to update lol
Possibly
How difficult is it to write a proximity voice chat? And would it be possible to have like a digital microphone which "records" your voice differently depending on where you are standing
basically would be passing it thru some sort of filter
why cant i add my own font to TextMeshPro?
You need converter
i think im blind one sec, but thank you :)
i think i got it
idk if im doing something wrong, but i got this now but i cant drag it in
it's pretty confusing, maybe this will help http://www.digitalnativestudios.com/textmeshpro/docs/font/
thanks ill read it!
iirc once the asset exists, you should see the font in the fonts dropdown (you don't drag it in)
alrighty, well i dont see it in the dropdown so i have done something wrong hahah, but ill read the doc
(it's possible that you do have to drag it in and i forgot)
dw im sure ill figure it out :)
When i disable a gameobj can i still trigger funktions inside a script of it?
Yes but unity won't run any message functions on it like Update
so you'd need to call a function manually
ik
Yeah, being a disabled MonoBehaviour means very little
when i drag the font asset in it doesnt appear as that font and i get this error
wait i think i got it to work
So im following a tutorial about a pause menu, what actually is the difference with normal text and TMP?
normal text is old and crappy and everyone ended up using TMP so unity bought TMP and made it the default
ahh okay okay, so technically it doesnt really matter if you use TMP or not
how do i check what direction my player is facing
transform.forward is a vector pointing in the forward direction of the transfomr
well, i'm trying to use rigid body add force in a way where it pushes me backwards from where i'm facing
in that case, -transform.forward will be a vector pointing backwards
there's no transform.back, annoyingly
ah
i see
correct me if im wrong but rb.addforce(-transform.forward) will not work right?
That will apply one newton of force. The force will point backwards.
One newton is enough to accelerate one kilogram at one meter per second per second. It's not very strong.
oh that's very nice
how would i add more force?
-transform.forward * forceAmount
because the amount of force applied is the length of the vector
oh right
this will explain all
transform.forward is a unit vector; it has a length of 1
since it's apply 1
oh neat, that's a useful resource
it's applying 1 and 1 * whatever number is yeah
okay thank you guys
so it's pushing me upwards
which is quite interesting
Then that's the direction the object is facing
Or rather the opposite of the direction it's facing
when the player press the key d
the player moves
but it mantains a certain speed when the player releases it's key
I don't c#
What is the "else" statement that can be added to maybe rb.AddForce(0,0,0)
can set the rigidbodies velocity to zero in the else statement
Adding zero force wouldn't do anything, kind of by definition
also what do the other forcemodes do? they were kinda the same when i tested
😔
so there is a speed variable
what?
I KNOW RIGHT
<@&502884371011731486>
incomprehensible
Also in what way is "Adding zero force results in zero force being added" in any way a strange thought
you my friend are so toxic
@open apex @snow girder homophobic comments are not tolerated here
you most likely don't have friends
the software is not a person
my bad
And if you continue, you're getting kicked. So move on.
it's an it
insanity
Why can we serialise fields using the [SerializeField] attribute to enforce encapsulation but not for methods?
I often find myself in the need where I "just" want to have a public method because I may have to select it from the Unity inspector window in events, animations, etc.
what does translate mean?
and what are some other examples you can use "Translate" in?
gotchu!
The mathematical process of moving something on a graph to a different place:
Does anyone know how to make that text delete after half a second?
This is what I use but it doesn't work
Well, that'd destroy it after three seconds
That is how, assuming you pass in the actual GameObject
If you pass in a component, it will destroy that instead
Ik but even after 3 seconds it was not destroyed
Half a second would be 0.5f
When do you run that code
and what is currentText
maybe just post !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Are you calling destroy on the correct object?
ok
might be a dumb question, but im watching a vid about a pause menu, im sure im doing something wrong but i dont know what, first pic is his code
You have to finish writing it
my bad i just noticed xd sorry
I'm gonna be asking a bit of dumb questions for yall since I'm new to coding
what's a method?
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/methods
You might also know it as a "Function"
So, that's definitely destroying the text object you just spawned
Are you getting any errors in the console
Well, someone have ideia how to solve it?
Yeah so that stops any code after it from running
You should also read the message above the error as to why you're getting it
You can't add a TextMesh to this object, it already has a mesh renderer
Consider moving line 22 and 23 before line 18
in the highlighted area, how does the math work here?
Better consideration: Make the prefab of the type you actually want so you don't need to fiddle with getcomponents
it scales the vector by Time.deltaTime, then by 20
correct, but how does the math work with it?
like how does time.deltatime multiply by 20
deltaTime is the value in seconds the last frame took to render. When you multiply a value in Update by that, it turns that value from "Units per frame" to "Units per second". In this case, it's moving the object by 20 units forward every second
by order of operations, though, it doesn't actually multiply deltaTime by 20
((Vector3.forward * Time.deltaTime) * 20)
same difference, though.
It didn't change anything but thanks anyway!
so it's 1 x 20?
where did the 1 come from?
1 x 20 x [The time it took to render this frame]
The length of forward
ah, you're talking about the length of the vector, yeah
I thought you had turned deltaTime into 1
what's the time?
is it random?
Depends
That's why it's a variable you use instead of hard-coding in a framerate
That as well. Wasn't a part of the person's error but evaluating destroy before calculating damage was probably unwanted.
I see
Because you don't know how long that frame will take to render
so what to do?
and im sorry im just a begginer
Don't try to add a TextMesh to a prefab that already has a MeshRenderer. Why are you trying to add one at runtime instead of just putting it on the prefab to begin with?
Reference it as the correct type.
public Whatever ... instead of GameObject.
This would ensure whatever you've dragged into that field (available in the inspector) would have an appropriate component.
Thank you very much, but what should I write instead?
The type you actually want to use
I just started on unity hub I created a project I wanna make it 2d but I'm stuck and don't know what to do
What are you stuck on
I'm on mobile and using swype but it would be as suggested, the specific component type that you're wanting to access.
@polar acorn @ivory bobcat 💀
what
That's because it's a TextMeshPro and not a TextMesh
Yes and if your variable were using an actual component type instead of GameObject you would have noticed sooner
ik
but thank you for the time
I appreciate it
should I be using arrays of lists for an inventory system?
There's not really a "should be", you use whatever data structure your particular implementation of an inventory would need
{
if(collision.transform.gameObject.name == "Player")
{
CM.Play("FadeToBlack");
StartCoroutine(WaitForFade());
}
}
IEnumerator WaitForfade()
{
yield return new WaitForSeconds(1f);
SceneManager.LoadScene("basement");
}```
i dont understand why its saying my coroutine doesnt exist
Where do you define WaitForFade
because it doesn't
read the code
i didnt but how comes if i put this line in void start() it does workStartCoroutine(WaitForFade());
bet
Where do you define a coroutine named WaitForFade
do you have a method called WaitForFade somewhere?
no
then that line cannot work
why does it work in void start tho
it doesn't
It doesn't
look carefully
StartCoroutine(WaitForFade());
IEnumerator WaitForfade()
i wanna die
make sure that your !IDE is configured so that you don't make silly spelling mistakes like this moving forward
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
is it best practice to make Action events static?
public static event Action<float> OnBetAmountUpdated; this is what i have in my "SlotMachineController" script
i've been wondering if i should make it a singleton as well, because it's the only one on the scene 🤔
Depends on whether you might need per-instance events. For example, are there multiple slot machines who'd need to fire their own OnBetAmountUpdated to their own listeners?
oh , so okay so i only have one. so if i have multiple gameobjects that i want events on (eg. if i had a game with enemies) then don't use static. if i only have one , use static. is that good way to decide?
Basically
If you want everything subscribed to this event to get notified, you can use static
just to make sure I understand this code
this code makes a gameobject, and the gameobject that goes inside of it will be the thing that the line of code will control, basically, the gameobject player will be the same as the attached script object?
also why did we use position, why not translate?
ok, because i was watching a tutorial on it last night. what the guy did was make a whole new script just for actions and made it static altogether (even though his game had multiple enemies and would send events on enemy death).
This code doesn't make a game object
this code sets this object's position to the position of whatever you've dragged in once per frame
yee sorry this is what I meant
so basically, whatever position the "player" is, the camera will follow it?
It sets the position of the object this script is attached to, to that of what's referenced per frame.
The camera would be at the same location per frame via teleport.
shouldnt we also add time.deltatime to the code?
For what?
Hello, i have questions about Text Mesh Pro:
For some Reason i unity and visual studio (unity hub install) dont accept
using TMPro;
Ive tried to ReImport all
Reinstalling TextMeshPro
Switching between "Open by File Extension" and Visual Studio
Downgrading and Upgrading(updating) Visual Studio
I found someone saying that i need to add TMPro to my package,json but i havnt found that json anywhere
go into the package manager and see if you have TextMeshPro installed. if you do, then you may be using assembly definitions and would need to reference the TMP assembly in your asmdef
can I have null gaps in a list or does it automatically resize to fit
We'd write code to accomplish an objective. Why/where do you want to use delta time?
do you have it here?
List and array can both contain null elements, yes
so the camera moves in seconds and not frames?
why am i getting out of range exceptions then
how should i know? you haven't bothered sharing the error or the code
go into the package manager and see if
sorry, no need to be rude bro
{
for (int i = 0; i < Inventory.Capacity; i++)
{
if (Inventory[i].item == _item && RemainingSpaceInSlot(i) > _amount)
{
Inventory[i].AddAmount(_amount);
OnItemsUpdated?.Invoke();
return true;
}
}
for (int i = 0; i < Inventory.Capacity; i++)
{
if (Inventory[i].item == null)
{
Inventory[i] = new ItemStack(_item, _amount);
OnItemsUpdated?.Invoke();
return true;
}
}
return false;
}```
The camera isn't moving by any amount, it's just setting its position to a precise value
private List<ItemStack> Inventory = new List<ItemStack>(54);
that is how i made the list
gotchu! I undetsand. ||(I do not understand 💀 🙏 )||
you're looping until you hit the list's Capacity which could be much larger than the number of elements contained in it. use its Count property instead
DeltaTime is for converting a value in "units per frame" to "units per second".
Nothing in this code is changing anything by "units per second"
It's just teleporting to that exact spot
OHHH
got it now
ty!
It's the opposite conversion
The way I think of it is, the value without Time.deltaTime means "Move this number in one frame", and with it it means "Move this number in one second"
Ah it's all just semantics again
If you're considering moving the camera towards the player, maybe use https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html or some other means (Rigidbody physics, CC, Cinemachine, etc
)
gotchu gotchu
just another quick question
I don't understand how we're using 2 vector threes, and why is there a "new"
You are adding a new vector to the player's position
That new vector having a value of 0, 5, -7
It's still not working, if I use count the loop is never reached
And the way I think about it is a value without delta time when applied already describes units/second, or is instantaneous. When applying dt you convert U/s to U/f
are you certain there is even anything in the list?
there isnt, im trying to add the first item
well then its count will be 0 because there are no elements in the list. you need to actually Add things to the list
new is necessary as part of C# syntax for new instances. Other than that, you've got an assignment of position with an offset: position = point + offset
but it doesnt make sense
if hte player transform position is changing with the player
What doesn't make sense about it
if the player transform position is changing with the player, how is there a 2nd one changing too?
You're setting the position of this object to the position of player plus some value
lmao
A second what
so it moves the "0" but keeps the "5" and "-7"
What
It adds the Vector 0, 5, -7 to the position of player, and sets this object's position to that result
Maybe look into c# tutorials and check out Unity tutorials for how to do simple stuff !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ohhhhhhhhhhhhhhhhhhhhhhh
so it sets it 5, -7 above the player?
like the location of the camera but it still follows where it goes
It sets it to the players location plus (0, 5, -7)
These are referring to coordinates (x, y, z) - Vector.
how do I actually-
make a unity project into a game/how I turn the unity project into an app?
not really a code question.
https://docs.unity3d.com/Manual/PublishingBuilds.html
sorry- wasn't sure where else to ask
but thanks
so the add is working but i'm having issues with swap, do lists not allow you to insert into a null index?
{
ItemStack itemOne = Inventory[indexOne];
if (Inventory.Count < indexTwo)
{
Inventory.Insert(indexTwo, itemOne);
return;
}
}```
basically when you try to swap with nothing it moves the item
have you even bothered looking at the docs to see what these methods do?
okay and tell me why you are using the Insert method then
im just asking in a beginner discord
Inserts an element into the List<T> at the specified index.
sounds like what i want
right it adds a new element to the list at the specified index
that is not what you want. you want to just assign to a specific element so it is no longer null
so what should I write?
if i just Inventory[indexTwo] = Inventory[indexOne]; it gives index error
that means that one or both of the indices is out of range
i know
why tho? i thought you could have null gaps in lists
my list capacity is 54
again, capacity is not representative of how many elements are actually in the list
Try printing indexTwo, indexOne, and the length of Inventory
a list can contain null elements. but you have to actually add them in
See which one is the problem
I know what is going on, i just dont understand the functionalities of lists it seems
okay so initilize the whole list with null
there are beginner c# courses that teach you how to use collections like lists and arrays pinned in this channel. you should start there
why is it even a List and not an array if you want a predefined number of elements that default to null
should I just use arrays?
probably
okay
insert normally means to slide in an entry into the middle of a list
oh and shift everything up
and it costs time because you’re actually shifting the memory for everything after
oh yeah- and is there a method to fetch a gameobject that was just instantiated by the script?
Yes, Instantiate
Instantiate gives you a reference to the thing it just made
oh
what's that?
Hi, i am looking for a project template to realize a webview app. Is there a template which is recommended for such a project? I want to display my own website. No matter of costs. If it is a one-time fee.
this is a unity server mate
But can anyone here help me with my Spanish homework?
or do you mean you want to display your website inside your unity game? 🤔
Or display a unity game inside a website maybe?
Yes i know. 😄
With unity its easy to build apps for different platforms. And there are many Webview Templates in the assetstore. I just ask if somebody can recommend a template.
okay so to confirm, you are referring to displaying your own website within your unity game?
and if the question is literally just about which asset you should pick, that isn't a code question
https://assetstore.unity.com/packages/tools/gui/in-app-web-browser-57532
This for example is a web browser. I could make a app which is showing my website.
again, not a code question
how does multiplying the inputs work?
I undetsnad how this works but after adding the verticalInput and horizontalInput, I don't understand how the math work with these two in them
what type is verticalInput
you should multiply the floats together first by surrounding the lot with brackets to avoid some extra multiplications
They're values that are between -1 and 1 depending on direction
👍
you should just make a single Vector3, and translate by it
remember the input is dimensionless, btw
which is part of how everything works out in the end
Is Angle an actual angle or is it a direction vector
the "explosionHits.remove(collider)" line should remove all colliders from the list, right?
at moment i'm using that angle for raycast, i suppose it's Direction vector
It seems like it's a Quaternion
because it does not seem to be working
to be fair idk
for example i can get position if i want forward cordinates like this
Vector3 EndPoint = transform.position+(transform.forward * _Distance);
But i need transform.forward +Angle
Do you have any errors? Shouldnt be able to remove items from a collection while iterating through it
its a ToList- to prevent that error
whats the best way to have a boss with multiple stages should i spawn a different object or just change the script or smth
okay is there a way to remove all colliders from a list then?
There should be a list.Clear()
oh okay thanks
Rule of thumb, if you are removing from a List, iterate backwards
im trying to do 2d movement and i can't figure it out
im just not to sure what to do with vector2
Hello, is there an option in unity 2D that prevents the player from being blocked by the tileset because of the Rigidbody?
Did you try the rigidbody ?
i dont know how to do rigidbody movement
did you already add a component ?
wdym by blocked by the tileset? are you referring to the issue where your rigidbody is getting stuck on the edges of tiles sometimes? or do you mean something else?
that's exactly what it is !
yes
that's a known issue with the Box2D physics engine which is what unity uses for 2d. you can use a collider that has a round bottom like a circle or capsule instead of a box collider. and turning the collision detection mode to continuous on the rb should help too
with unity you can use the velocity of a rigidbody, That's look like that "rb.velocity = new Vector2(deplacement, rb.velocity.y);",
there is a widespread technique that consists of adding horizontal keys to move your player in a desired direction "Input.GetAxis("Horizontal")". Basically, this function registers the left directional key as =-1 and right = 1, and when you press it, the value takes the key you pressed (otherwise it returns zero).
finnaly you can make the command like that:
horizental = Input.GetAxis("Horizontal");
"rb.velocity = new Vector2(horizental* deplacement, rb.velocity.y);"
rb.velocity.y returns the current value of your y velocity rigibody
yes i know that but my camera glitch a little with that ;-;
then you also need to address how you control your camera
and obligatory: use cinemachine
i think i will use 2 box
but thanks for your tips
im still confused
did you already give a variable for a gameobject ?
for the rigided body?
yes
yes
a public rb
yes
I have this weapon switch problem. Lets say Gun1 has 10 bullets and Gun2 has none. When I switch to Gun2, I can shoot only one bullet as if it registers the weapon switched when I click.
If you want me to send the scripts I can
yes, we'll need to see your code
How to post !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using UnityEngine;
public class WeaponSwitching : MonoBehaviour
{
public int selectedWeapon = 0;
private void Start()
{
SelectWeapon();
}
private void Update()
{
int previousSelectedWeapon = selectedWeapon;
if (Input.GetAxis("Mouse ScrollWheel") > 0f) {
if (selectedWeapon >= transform.childCount - 1)
selectedWeapon = 0;
else
selectedWeapon++;
}
if (Input.GetAxis("Mouse ScrollWheel") < 0f) {
if (selectedWeapon <= 0)
selectedWeapon = transform.childCount - 1;
else
selectedWeapon--;
}
if (Input.GetKeyDown(KeyCode.Alpha1)) {
selectedWeapon = 0;
}
if (Input.GetKeyDown(KeyCode.Alpha2) && transform.childCount >= 2) {
selectedWeapon = 1;
}
if(previousSelectedWeapon != selectedWeapon) {
SelectWeapon();
}
}
private void SelectWeapon()
{
int i = 0;
foreach (Transform weapon in transform) {
if ( i == selectedWeapon )
weapon.gameObject.SetActive( true );
else
weapon.gameObject.SetActive( false );
i++;
}
}
}
This weaponSwitch script works fine, I even tried another method so I think its something else causing this problem
What's the original problem?
Lets say Gun1 has 10 bullets and Gun2 has none. When I switch to Gun2, I can shoot only one bullet as if it registers the weapon switched when I click.
where do you actually shoot?
where? like the script
So.. you shouldn't be able to shoot any at all but are somehow allowed to shoot one shot?
yes the code
Where's your shooting code?
Please post the code using an external service link if greater than 15 lines or so.
Like this for example using your previous code: https://gdl.space/pobozuleje.cs
So, the gun isn't reloading and the elapsed time since last fire is valid.
I'm assuming these are the limiting factors in allowing you to shoot
Other than gunData.currentAmmo > 0. @faint agate
Log the gunData
Is this related to Unity and coding?
yes its from their website.
I'm assuming this isn't related to coding, try #💻┃unity-talk
to see if its Gun1's bullet?
To see if it's the correct gun
Gun2 doesnt even have the gun script on it. If switching the gun disables Gun1 and all its childs, than idk how Gun2 is even shooting one bullet.
Did you try logging?
Why is this giving out of bounds access?
{
public event Action OnItemsUpdated;
private ItemStack[] Inventory = new ItemStack[54];
[SerializeField] private ItemStack itemTest;
void OnEnable()
{
for (int i = 0; i < 54; i++)
{
Inventory[i] = new ItemStack();
}
}```
Your array size isn't 54
before I go and make it from scratch is there a easily implemented system that lets the player control the camera in runtime? Basically just like in editor mode.
I logged it, it is Gun1's bullet
Try:cs void OnEnable() { Debug.Log($"Inventory Size: {Inventory.Length}"); for (int i = 0; i < Inventory.Length; i++) { Inventory[i] = new ItemStack(); } } @native seal
Inventory Size: 54
UnityEngine.Debug:Log (object)
InventoryObject:OnEnable () (at Assets/_Scripts/Scriptable Objects/SO Scripts/Inventory/InventoryObject.cs:43)
On the player, theres a player shoot script that might give you a bit more info.. one sec
When I switch to Gun2, I can shoot only one bullet as if it registers the weapon switched when I click.
So Gun1 fired that last shot and not Gun2.
it is 54
Figure out why Gun1 is firing when you'd expect the shot to be from Gun2
The above should not ever throw.
so what is going on
Previously, we were assuming that Inventory that should have 54 elements but it likely did not if there was an out of bounds error.
so what do I need to change
Show the actual errors and we'd be able to validate if the error was real or not.
The console window
wait i think its an issue with onenable with scriptable objects
thats what im confused about. I removed the gun script from Gun2 so its just a cube. When I switch to it, Gun1 and all its child gets disabled, so it should be imposible for me to shoot. I sent the playershoot script attached to the player that might be the problem
Log why it can shoot.
So ignoring Gun2, Gun1 is still allowed to fire when disabled.. why?
Log the state of Gun1 on shoot.
Log ammo count, can shoot and whatnot.
They are the limiting factors.
where n how would I log this, I logged the ammo count and it does go down by that one shot.
I logged to see when it was holding gun 2
it said I was holding Gun2 so idk
Debug.Log($"{name} has {gunData.currentAmmo} ammo left");
Debug.Log($"It isn't reloading: {!gunData.reloading}");
Debug.Log($"Time since it last shot: {timeSinceLastShot}");
Debug.Log($"Time till it can shoot again: {1f / (gunData.fireRate / 60f)}");
Debug.Log($"It can shoot: {CanShoot()}");```
would I put all that on update
if so, I did and when I switched to Gun2, it all stopped
You'd put all of this in the shoot function...
Before the if-statement.
what diffrence am I looking for, it says all the same stuff when I switch and shoot the one bullet. When I try to shoot a second time nothing prints
Can you show the logs?
I really think it has something to do with the playershoot script. It's connected to the gun script but its attached to the player and since Gun1 disables. this is the only thing allowing it to shoot a second time mabye
thats the playershoot script
Not relevant. As far as I'm concerned, the object hasn't called it's OnDisable method.
Question would be why? Did the final shooting and weapon swap occurred immediately at the same time or do you've got some delay to not disable to object till after the final shot?
how do i use variables inside of a string, the variable name would be inbetween the {}
i didn't know how to explain this to google so here i am lol
string interpolation is the name
where did i read tokens from lol
token refers to the $ you must put at the front
alr
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering.Universal;
public class LightSwitch : MonoBehaviour
{
public Light2D L;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
StartCoroutine(SwitchTime());
}
IEnumerator SwitchTime()
{
yield return new WaitForSeconds(0.5f);
L.enabled = true;
for(float i = 0; i < 1.8; i =+ 0.05f)
{
L.intensity = i;
}
}
}
``` why is this crashing my unity every time the coroutine is called
That for loop.
Incrementation should be +=
right
= +0.1 would just be assigning it the value of 0.1
Also, just to let you know that what happens after in the for loop would happen immediately the current frame with no delay.
Maybe consider: cs IEnumerator SwitchTime() { yield return new WaitForSeconds(0.5f); L.enabled = true; for(float i = 0f; i < 1f; i += Time.deltaTime / 1.8f) { L.intensity = i; yield return null; } }if you're wanting a delay + transitioning of intensity over time.
There isn't much to work with. Likely you've got a rounding error or the math is wrong.
Maybe log some position to see why it doesn't go where you're expecting it to go.
use Mathf.RoundToInt, Mathf.CeilToInt, or Mathf.FloorToInt depending on what operation you actually want, instead of directly casting to int and hoping that it it works out
im trying to make my first basic project with a light switch and ive been trying to make it so that when i click the switch, the value of TimesClicked goes up by 1 and is then read as text in the game. i keep getting issues converting int to text. i know its easy but i need some help.
Image
It's okay the bot will show up in a bit
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
Bot seems to be down
there it is
VS seems to be up to date but i still cant see the errors underlined
If it's not underlined then it's not configured. Maybe the bot is back alive again? !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
there it is
well i went to the website and i checked the instructions it had
and it didnt change anything
Reopen VS via Unity's Assets/Open C# Project
if it's configured fully it should start working
how do i open it via unitys assets, do i just open a new script?
The menu Assets/Open C# Project
No, just configure it properly using all the instructions on the page
Making sure it has the Unity workload installed, making sure Unity's External Tools preferences are set, making sure the VS Editor package is up to date in Unity
how do i access the dropdown list
please be more specific
"It's possible to select other versions of Visual Studio that are unlisted and installed in a custom directory.
Select Browse... from the dropdown list."
im not where the dropdown list is
yes i see that but where do i find the devenv.exe directory
Wherever VS is installed
like on the VS installer?
It says it's within the Common7/IDE directory, where VS is installed
Presumably VS is installed in program files
Does your drop down box not have Visual Studio available?
usually, unless u went out of ur way to install it elsewhere
anyone know for this
dis new?
Not really a coding question. You could probably ask #💻┃unity-talk
ok
don't recall ever seeing it, might try out playerprefs for my new prototype
oh nice, for some reason i was thinking playerprefs was PC only..
im sure theres a few lurking around
How exactly are you moving it? If the concept of being in a tile entirely is important for your game, it should be incorporated in movement logic.
I found that and i selected devenv.exe and i think its showing red squigle lines
i'd use a basic state machine using enums
basic state machine?
isnt that for animations
well, the animation system is a statemachine..
but they have many uses..
https://gamedevbeginner.com/state-machines-in-unity-how-and-when-to-use-them/
Okay vertx i wanna thank u so much
i know that was really stupid
but thanks it works and i found the issue
That doesn't explain much.
But if you want it to be an actual snake game, where the game space is divided into discreet tiles, you'll need to move the object such that they are always within a tile or in a temporary moving state between tiles.
can define ur own enums, have like Boss_Idle, Boss_Stage_1, Boss_Stage_2, Boss_Defeated and could have different actions or code run during each state
its one of those things you'll repeatedly end up using, good to go ahead and learn about em, atleast to expose urself to em
lol, i agree, imo a snake game really isnt a snake game unless its based on tiles, and it moves by enabling the first most and disabling the last most tile 😄
one says Vector3.start one says Vector3.origin, is there adiffereence between the two?
no
i feel its cheating to have a snake game that uses normal transform translation lol
alright thanks
Also they don't say Vector3.start or Vector3.origin, they're just parameter names, there is no .
oh yeah
you're a beginner?
if you go with an RPG, go basic as possible
i mean extremely basic
why does this register as a hit?
the hitbox it hit is highlighted here
and there are some barely visible green raycasts
why are your gizmos so invisible
the perspective of that is really confusing lol
high resolution screen
and idk how to increase raycast thickness
well drawRay thickness
or visibilty
they should still be 1px wide and full color
they are 1px wide but I have a 2560x1600 screen
nvm turned 3d gizmos off
and my stuff looks totally fine
what im i doing wrong here, it says there are two errors, this is getting annoying
3d gizmos apparently murders drawRay
where are the errors?
I'd do it with lerping instead of velocity, but it's not impossible with velocity or even both
Here's some pseudocode to give a thought:
if !moving and input != 0
moving = true
nextDestination = currentTilePos + input //here both tile position and input should be a discreet number, so that you get the next discreet tile position
t = 0
if moving
t += deltaTime;
position = lerp(currentTilePos, nextTilePos, t)
if t >= 1
moving = false
currentTilePos = nextTilePos
alright the same bug recreated - what causes this to read as a hit?
it would be easier if you also did:
Debug.DrawLine(ray.origin, hit.point);
Debug.DrawRay(hit.point, hit.normal, Color.red);
!docs
One is a line. The other is a ray.
one goes forever?
I mean to draw the ray and the hit, instead of just drawing the complete cast without knowing where it terminated
No
whats line vs ray difference
read the documentation.
One is between 2 points. The other has an origin and direction.
ah yeah ok
But do read the docs
alright
yeah realized now
i was already painting.. had to finish
mathematically though unity rays function kinda like line segments since they still have a finite length
and mathematically lines are also line segments
(the mathematician in me speaking)
Vector3.forward * Mathf.Infinity;
so true
but yea, u got the idea
but for the debug code you gave me, what would the point ray.origin be?
the origin of the ray
so just transform.position?
yes
https://gamedevbeginner.com/the-right-way-to-lerp-in-unity-with-examples/
really simple brief
If I have this
[System.Serializable]
public class Wave
{
public string name;
public GameObject enemyPrefab;
public int count;
public float rate;
}
How Can I get access to the enemyPrefab for each wave?
referenceToWave.enemyPrefab;
also what does the console say?
where is that on there?
Any
hmm I don't see collision geometyr
Can you move the window so you can actually see the bottom right of the scene view?
Can you see what it's hitting now?
its hitting something with a different layermask
it's hitting something with mask fakeWall but the mask says to only hit realWall
show how you declare the mask
and show the object it's hitting?
wait nvm it still says its hitting WallEZ
wallEZ is the only rendered wall here
and thats what the debug log says its hitting
with its hitboxes highlighted
Can you add the object to your log so you can ping it when the log is selected https://unity.huh.how/debugging/logging/how-to#the-context-parameter
already did
No, you didn't
Did you read the link they sent?
It's about the second (context) parameter of Debug.Log
so would this ping it?
Yes
what does the ping look like because there are no visible changes
You can just copy code in instead of a screenshot btw. Much easier to read
my code
ah true
Debug.Log($"Hit object {hit.transform.name}@{hit.transform.position} from {transform.position} with run index {i}", hit.transform.gameObject);
Debug.Log($"Hit object {hit.transform.name}@{hit.transform.position} from {transform.position} with run index {i}", hit.transform.gameObject);
You can click the log in the console and it will show you which object is logged in the hierarchy
oh ok