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();
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.