Infinite loop symbole in town

Unity – Yield return null

In Unity, yield return null is used in a coroutine.
It allows code to be executed just after the Update function.

Inserted in a while(true) loop, it limits code execution to once per frame.

How do I use yield return null?

You have to create a coroutine, then insert yield return null in it.
As a reminder, a coroutine is simply a function returning an IEnumerator.

In most cases, the instruction is placed in a while loop, thus avoiding the formation of an infinite loop.
In a while loop, the coroutine becomes an alternative to the MonoBehaviours Update function.

using System.Collections;

public void CoroutineLauncher()
{
	StartCoroutine(CoroutineAction());
}

private IEnumerator CoroutineAction()
{
	while(true)
	{
	    // your actions here
		yield return null;
	}
}

At the timeScale level, the coroutine acts like the Update function: the number of calls per second does not vary.

For people who learned C# before using Unity, you may be surprised by the use of yield like this.
In C#, the yield statement provides the next value in an iterator.
For example, the List class uses an IEnumerator to loop through these values.

See Microsoft’s official documentation on yield.

On Unity, we’re moving away from its default use to create a kind of “hack” that allows us to limit the execution frequency of our code.

Execution order with yield return null

yield return null provides a concrete alternative to an Update function.
In execution order, yield is called just after the Update function.

Except for yield WaitForFixedUpdate, his execution begins at the end of the physical part.
Same for yield WaitForEndOfFrame, his call takes place at the end of the frame.

As a reminder, on Unity, the order of execution is as follows:

  1. Initialization: Awake, Start, etc.
  2. Physics
  3. Input
  4. Update
  5. yield (null, WaitforSeconds, WWW…)
  6. Animation
  7. LateUpdate
  8. Rendering
  9. Decommissioning: OnDisable, OnDestroy, etc.

unity script lifecycle flowchart
The diagram above is from the official Unity documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *