Coroutines and IEnumerator
A regular method runs to completion within a single frame. A coroutine can pause itself and resume later, spread across multiple frames, without blocking the main thread. Unity coroutines are built on C#'s IEnumerator.
using System.Collections;
using UnityEngine;
public class FadeIn : MonoBehaviour
{
void Start()
{
StartCoroutine(Fade());
}
IEnumerator Fade()
{
CanvasGroup group = GetComponent<CanvasGroup>();
float t = 0f;
while (t < 1f)
{
t += Time.deltaTime;
group.alpha = t;
yield return null; // pause until next frame
}
}
}
The pieces
- A coroutine is any method that returns
IEnumeratorand contains at least oneyield return. StartCoroutine(...)begins running it, Unity resumes it each frame from wherever it lastyield returned.yield return nullpauses for exactly one frame.yield return new WaitForSeconds(2f)pauses for 2 (scaled) seconds.
Why not just Update()?
Update() runs every frame for the entire lifetime of the object. A coroutine only runs while it has work to do, then finishes, better for one-off timed sequences like fades, delays, or spawn waves.