unity3d Coroutines

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  • public Coroutine StartCoroutine(IEnumerator routine);
  • public Coroutine StartCoroutine(string methodName, object value = null);
  • public void StopCoroutine(string methodName);
  • public void StopCoroutine(IEnumerator routine);
  • public void StopAllCoroutines();

Remarks

Performance considerations

It's best to use coroutines in moderation as the flexibility comes with a performance cost.

  • Coroutines in great numbers demands more from the CPU than standard Update methods.
  • There is an issue in some versions of Unity where coroutines produce garbage each update cycle due to Unity boxing the MoveNext return value. This was last observed in 5.4.0b13. (Bug report)

Reduce garbage by caching YieldInstructions

A common trick to reduce the garbage generated in coroutines is to cache the YieldInstruction.

IEnumerator TickEverySecond()
{
    var wait = new WaitForSeconds(1f); // Cache
    while(true)
    {
        yield return wait; // Reuse
    }
}

Yielding null produces no extra garbage.



Got any unity3d Question?