Coroutine beginner

Hi there,

First time C# coder here. I was curious if someone could point to me how to start a coroutine at a specific time in the game. I’m looking everywhere but fail to understand how to do it. I stumbled on code such as the following, but it doesn’t work, Unity comes back with a host of errors in the Console. All I really want to do is StartCoroutine after x seconds from the beginning of the game.

void Start(){
    Invoke(2.0f, "MyMethod");
    StartCoroutine(Delay(2.0f,MyMethod))
}
void MyMethod(){Debug.Log("Call");}
IEnumerator Delay(float timer, Action action){
    while(timer > 0f){
        timer-=Time.deltaTime;
        yield return null;
    }
    if(action != null){
        action();
    }
}

source: Coroutine usage – Delay – UnityGems

Thank you for your time, I hope I was succinct enough.

This fixes your errors

void Start()
{
    Invoke("MyMethod", 2.0f);
    StartCoroutine(Delay(2.0f, MyMethod));
}

void MyMethod()
{
    Debug.Log("Call");
}

IEnumerator Delay(float timer, Action action)
{
    while(timer > 0f)
    {
        timer-=Time.deltaTime;
        yield return null;
    }

    if(action != null)
    {
        action();
    }
}

And you can get more information about coroutines by checking the documentation out

  1. Coroutine
  2. StartCoroutine
  3. WaitForSeconds

Taken from the StartCoroutine documentation page -

The execution of a coroutine can be paused at any point using the yield statement. The yield return value specifies when the coroutine is resumed. Coroutines are excellent when modelling behaviour over several frames. Coroutines have virtually no performance overhead. StartCoroutine function always returns immediately, however you can yield the result. This will wait until the coroutine has finished execution.

The IEnumerator allows the program to yield things like the WaitForSeconds function, which lets you tell the script to wait without hogging the CPU