Unity - IEnumerator's yield return null

WonderfulWonder picture WonderfulWonder · Jan 18, 2017 · Viewed 41.3k times · Source

I'm currently trying to understand IEnumerator & Coroutine within the context of Unity and am not too confident on what the "yield return null" performs. At the moment i believe it basically pauses and waits for the next frame and in the next frame it'll go back to perform the while statement again.

If i leave out the "yield return null" it seems the object will instantly move to its destination or perhaps "skip a lot of frames". So i guess my question is how does this "yield return null" function within this while loop and why is it necessary to have it.

void Start () {
    StartCoroutine(Move());
}

IEnumerator Move(){

    while (a > 0.5f){

        ... (moves object up/down)

        yield return null; // <---------
    }

    yield return new WaitForSeconds(0.5f);

    .... (moves object up/down)

    StartCoroutine(Move());
}

Answer

Everts picture Everts · Jan 18, 2017

The program will start the loop, if you had no yield, it simply runs all iterations within the same frame. If you had millions of iterations, then it would most likely block your program until all iterations are done and then continue.

When creating a coroutine, Unity attaches it to a MonoBehaviour object. It will run first on call for the StartCoroutine until a yield is hit. Then it will return from the coroutine and place it onto a stack based on the yield. If you yield null, then it will run again next frame. There are a number of different YieldInstruction's that can be returned from a coroutine, you can read more about them here and through the related links.

Once a coroutine has yielded, the Main Thread continues running. On the next frame, Unity will find stacked coroutine and will call them from where they left off at the yield. If your coroutine never runs out of scope then you basically created an update method.

The purpose of coroutine is to perform actions that could span over a period of time without blocking the program.

IMPORTANT FACT: this is not multi-threading.