Yield return null?

Please someone explain to me what is “yield return null” in coroutines?

For example if we have this code…

void update{
   StartCoroutine(MoveEnemy());
}

IEnumerator MoveEnemy(){
   While(true){
      somecode...
      yield return null; // Whats the use of this line?
   }
}

I know it means run the code until the next frame, but what does that even mean?

Thank you.

The yield keyword is not a Unity feature. It’s a C# feature called “iterator block”. It allows to easily write iterator objects. The C# compiler actually turns your coroutine method into a compiler generated state machine class.

Unity uses those to implement coroutines. They are actually meant for things like this:

IEnumerable<int> SomeIterator()
{
    yield return 0;
    yield return 42;
    yield return 7;
    for (int i = 0; i < 10; i++)
        yield return i*2;
}

This is also called a “generator method”. When you call this method you actually create an instance of the internally generated statemachine class which implements the IEnumerable interface. This can be used for example in a foreach loop:

foreach(int val in SomeIterator())
{
    Debug.Log(val);
}

This will print those 13 values: 0, 42, 7, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18. In Unity’s coroutines Unity uses the value you return to determine when to continue / iterate your statemachine. If you return the value null (or any other value Unity doesn’t recognise) Unity will simple re-schedule the coroutine the next frame. However if you return an instance of the WaitForSeconds class, Unity will wait for the specified time until it continues your coroutine.

This great blog article (which unfortunately only exists in the web archieve) explains this quite well with a simple example

Short answer:

yield return null - wait for the next frame and continue execution from this line

Unity performs many operations every frame:

  • Initialization
  • Physics Updates
  • Input processing
  • Game Updates (Update())
  • Rendering Graphics, GUI etc.

yield return null runs earliest of any other yield returns.

For eg: yield return new WaitForEndOfFrame() will work after yield return null.


Explaination:

When you use iterations (IEnumerator) without returns, Unity runs it countless amount of time in one frame, blocking the editor. Therefore, we have to use yield return to return the control back to unity as if it gains control back even for a split second the editor will not block.


You can know more about unity execution order from given flowchart: