Coroutines
Game logic is full of sequences that span many frames: flash red for 0.2 seconds, wait for the door to open, spawn a wave every 5 seconds three times. Writing them as timers and flags in Update gets messy fast. A coroutine lets you write the sequence top to bottom and pause it with yield return.
Coroutines in Unity
using System.Collections;
using UnityEngine;
public class DamageFlash : MonoBehaviour
{
[SerializeField] Renderer bodyRenderer;
[SerializeField] Color flashColor = Color.red;
static readonly WaitForSeconds FlashTime = new(0.1f); // cached: no allocation per flash
Coroutine running;
public void Flash()
{
if (running != null) StopCoroutine(running); // restart instead of stacking
running = StartCoroutine(FlashRoutine());
}
IEnumerator FlashRoutine()
{
var material = bodyRenderer.material; // per-instance copy of the material
Color original = material.color;
for (int i = 0; i < 3; i++)
{
material.color = flashColor;
yield return FlashTime; // resume after 0.1 s of scaled time
material.color = original;
yield return FlashTime;
}
running = null;
}
}What you can yield:
yield return … |
Resumes |
|---|---|
null |
next frame, after all Updates |
new WaitForSeconds(t) |
after t seconds of scaled time (stops while Time.timeScale is 0) |
new WaitForSecondsRealtime(t) |
after t real seconds (pause menus) |
new WaitForFixedUpdate() |
after the next physics step |
new WaitForEndOfFrame() |
after rendering (screenshots) |
new WaitUntil(() => cond) / WaitWhile |
when the condition becomes true / false |
another IEnumerator or StartCoroutine(...) |
when that coroutine finishes |
Lifetime rules: a coroutine belongs to the MonoBehaviour that started it. It stops when that GameObject is deactivated or destroyed (disabling just the component does not stop it), and it can't return a value or catch exceptions across a yield.
How it works: a model
A coroutine is just a C# iterator. StartCoroutine stores the IEnumerator; every frame, the engine checks what the iterator last yielded and calls MoveNext() when that wait is over. Here is that scheduler, running at a fixed 0.25 s per frame so the output is exact:
using System;
using System.Collections;
using System.Collections.Generic;
var runner = new CoroutineRunner();
runner.Start(Spawner(), "spawner");
runner.Start(Blink(), "blink");
for (int frame = 1; frame <= 12 && runner.Count > 0; frame++)
runner.Tick(0.25);
IEnumerator Spawner()
{
for (int wave = 1; wave <= 3; wave++)
{
Console.WriteLine(quot; spawn wave {wave}");
yield return new WaitForSeconds(1.0);
}
Console.WriteLine(" spawner done");
}
IEnumerator Blink()
{
yield return null; // wait one frame
Console.WriteLine(" blink on");
yield return new WaitForSeconds(0.5);
Console.WriteLine(" blink off");
}
class WaitForSeconds { public double Seconds; public WaitForSeconds(double s) => Seconds = s; }
class CoroutineRunner
{
class Routine { public string Name = ""; public IEnumerator It = null!; public double WakeAt; }
readonly List<Routine> routines = new();
double time;
public int Count => routines.Count;
public void Start(IEnumerator it, string name)
{
var r = new Routine { Name = name, It = it };
routines.Add(r);
Advance(r); // runs until the first yield, immediately
}
public void Tick(double dt)
{
time += dt;
Console.WriteLine(quot;t={time:F2}");
foreach (var r in routines.ToArray())
if (time >= r.WakeAt - 1e-9) Advance(r);
}
void Advance(Routine r)
{
if (!r.It.MoveNext()) { routines.Remove(r); return; }
r.WakeAt = r.It.Current is WaitForSeconds w ? time + w.Seconds : time; // null = next frame
}
} spawn wave 1
t=0.25
blink on
t=0.50
t=0.75
blink off
t=1.00
spawn wave 2
t=1.25
t=1.50
t=1.75
t=2.00
spawn wave 3
t=2.25
t=2.50
t=2.75
t=3.00
spawner done
Two details match Unity exactly: code before the first yield runs inside StartCoroutine, and WaitForSeconds resumes on the first frame at or after the deadline, so with long frames waits are rounded up to the next frame.
Coroutines or Update?
- Coroutine: sequences, cutscene-like scripts, things that happen once and finish ("fade out, load, fade in").
- Update + timer: continuous behaviour that is always running (movement, cooldowns you query).
Awaitable(async/await): sequences that need return values,try/catch, or cancellation from outside. See the next lesson.
Tip:
new WaitForSeconds(...)inside a loop allocates every iteration. Cache instances you reuse, as inFlashTimeabove, or useAwaitable.WaitForSecondsAsync, which is pooled.
Test yourself
When does code before the first yield return in a coroutine run?
- Next frame
- Immediately, inside the
StartCoroutinecall - After all Update calls
- After the next FixedUpdate
A pause menu sets Time.timeScale = 0. Which wait still finishes?
WaitForSeconds(1)WaitForSecondsRealtime(1)WaitForFixedUpdate()- None of them
What stops a running coroutine automatically?
- Disabling the MonoBehaviour component
- Deactivating or destroying its GameObject
- Changing Time.timeScale
- Calling Update