How to wait 2 seconds before activating a part of code?
my goal is to make the work after 2 seconds.
here is my code;
thank you! 🙂
16 Replies
Wait, why are you getting the rigidbody with each collision?
In normal C# you'd use
await Task.Delay(2000)
Just save the Rigidbody component in a variable and use that
Unity probably has its own weird thing
Unity has Coroutines
https://docs.unity3d.com/Manual/Coroutines.html
By default, Unity resumes a coroutine on the frame after ayield
statement. If you want to introduce a time delay, useWaitForSeconds
:
to be honest im not sure.
but will do that
GetComponent is expensive
So avoid calling it more than once if not required
well technically it will be called once so will it matter in this case? but yeah im getting rid of it
It's supposed to be called once, but what if you enter then exit and repeat?
You will be calling GetComponent more than once, which isn't needed.
Now it doesn't affect the performance that much, but it does help a little to cache it in a variable, depending on how frequent the calls are.
If you were calling GetComponent in Update, now that would be a fairly big impact.
yeah i get what you mean and it makes sense. but in this case when the player enters the object should fall down and be destroyed
but it will definetly be important on other things
Then yeah, it shouldn't make a big difference, except you use GetComponent when the component is loaded and not when the events happen.
Both being called once, so you'll be fine.
also on this link, im quiet confused on how i have to use it. i believe i have to be using right?
Correct
how may i apply this to my code?
Check the docs and scroll down until you see
Coroutine time delay
It shows an example of how it applies
Tasks are currently not recommended for Unity since it still runs even if you change the scene.
So unexpected things might / will happen.i think i managed to do it, thank you so much
ehh it didnt work im trying to find th issue here
yep it works now, thank you again. do i have to close this post now?