Nelson Yi
Nelson Yi

Reputation: 49

Unity C# waiting

Currently, I have this code

void update()
{
    Debug.Log(1);
    StartCoroutine(wait());
    Debug.Log(4);
}
IEnumerator wait()
{
    Debug.Log(2)
    yield return new WaitForSeconds(3);
    Debug.Log(3)
}

I want an output of 1, 2, 3, 4, but instead I'm getting 1, 2, 4, 3. I think I may be misunderstanding how coroutines function here. Why am I getting this behaviour and how would I go about fixing it? Thanks in advance

Upvotes: 1

Views: 1169

Answers (1)

Steven Coull
Steven Coull

Reputation: 478

To learn more about Coroutines, I recommend reading the excellent answer given here.

To give a high-level summary for your code, when you call StartCoroutine on wait(), all of the code until your yield statement will run. So now your output is 1, 2. When yield is called, Unity will return and execute the code in update(), logging the int 4. After 3 seconds it will return to wait() and continue execution, giving the final output 1,2,4,3.

If you want to output 1,2,3,4 you will need to use yield return to call the wait() method, so 4 is printed afterwards. In order to do this the code in update() will need to be in a method of return type IEnumerator itself.

void update()
{
    StartCoroutine(dosomething());
}

IEnumerator dosomething()
{
    Debug.Log(1);
    yield return wait();
    Debug.Log(4);
}

IEnumerator wait()
{
    Debug.Log(2);
    yield return new WaitForSeconds(3);
    Debug.Log(3);
}

Upvotes: 1

Related Questions