Coroutines (AKA Running tasks on the side)

How Coroutines Work

Coroutines can be used to spread tasks across several frames. At a basic level coroutines are functions that execute code in one frame until they hit a yield statement. Then then they pause execution until the next frame. In the next frame they then resume execution starting from the yield statement.

When Does The Body Of A Coroutine Function Run?

Coroutines typically run after the Update function returns. The execution inside can be paused and resumed be altered based on the type of yield expression used:

  • yield: Resume after all Update Functions are called.

  • yield WaitForSeconds: Resume after all Update Functions after specified time delay.

  • yield WaitForFixedUpdate: Resume after all FixedUpdate Functions are called. Can be invoked twice in the same frame if a yield was called prior to FixedUpdate.

  • yield WWW: Resume after WWW download has completed.

  • yield StartCoroutine("X"): Resume after coroutine “X” completes execution.

How Coroutines Stop

Coroutines stop under the following conditions:

  • They finish executing the coroutine function (No infinite yield loops)

  • The user executes StopCoroutine() on a specific coroutine or halts all coroutines in the script using StopAllCoroutines().

  • The game object the script is attached to is destroyed or sets SetActive to false.

    Note

    If you disabled MonoBehaviour by setting enabled to false Unity will not stop coroutines.

Basic Coroutines

Working With Multiple Coroutines