![]() |
VOOZH | about |
Coroutines in Unity are used to execute code over time instead of all at once, making them ideal for handling delays, animations, and asynchronous tasks without freezing the game. Unlike normal methods that run completely in one frame, coroutines can spread work over multiple frames.
A coroutine returns enumerate and uses yield return to pause.
Output:
StartCoroutine() begins the coroutine. yield return new WaitForSeconds(2f) pauses it for 2 seconds. The game continues running normally during the wait.
| Instruction | Waits for |
|---|---|
yield return null | One frame |
yield return new WaitForSeconds(2f) | 2 seconds |
yield return new WaitForSecondsRealtime(2f) | 2 seconds (ignores timeScale) |
yield return new WaitForFixedUpdate() | Next physics frame |
yield return new WaitUntil(() => condition) | Until condition is true |
yield return new WaitWhile(() => condition) | While condition is true |
yield return StartCoroutine(Another()) | Another coroutine to finish |
Output:
The while loop runs forever. After each spawn, it waits 3 seconds before spawning again.
Save the coroutine reference to stop it later. StopAllCoroutines() stops every coroutine on the script.