Are Coroutines the best way to delay ? If not, what is ? C#

Hello everyone :slight_smile:

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 :slight_smile:

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); 
 }

API documentation here

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); 
}