Are Coroutines the best way to delay ? If not, what is ? C#
Hello everyone :)
I'm doing my first attempt at creating a game and a few weeks back, I've read that when you wanted to delay something, coroutine was a good way to go. But recently, I've been felling like it's maybe not that good. So I did some research and indeed, it seems like coroutines are a debatable subject.
If I use coroutines exclusively for the "yield return new WaitForSeconds()", is that a good idea? If not, is there any other "simple" way to delay something that easily?
Thanks for any answer :)
Would like to bump this question if possible. I've been wondering the same thing. Would it be more efficient to keep track of Time.time and simple do a check in Update()?
I don't know for sure, but have a look at this. Especially those two $$anonymous$$oderator's comment. I would do the same.
Answer by connorwforman · Oct 27, 2017 at 03:19 PM
I would say yes. They are to use, but they can be a bit tricky to call. Here is an example how to use one. Let's say we want an object to appear 3 secs. after we enter a trigger. Coroutines with WaitForSeconds are always IEnumerator
's
public GameObject object;
public float Timedelay = 3f;
void OnTriggerEnter (Collider other) {
StartCoroutine (delay()); //There needs to an open/close parenthesis before the closing one.
object.SetActive (true);
}
IEnumerator delay () {
yield return new WaitForSeconds (Timedelay);
}
That's exactly how not to use coroutines. object.SetActive (true);
must be inside the coroutine.
Answer by unity_oeoSVeiNfO-Y8A · Oct 02, 2021 at 12:42 AM
Using MonoBehaviour.Invoke() instead of StartCaroutine() have possibility to invoke any method in class with delayed seconds:
public GameObject object;
public float TimeDelay = 1;
void OnTriggerEnter (Collider other) {
Invoke("MyFuncionFoo", TimeDelay ); //This will invoke your function after 1 second ...
}
void MyFuncionFoo() {
object.SetActive (true);
}