Game Development
What is a Coroutine?
Learn that Coroutines are used for work spread over time.
What is a Coroutine?
When a standard C# method is invoked, it runs from start to finish within a single frame. A Coroutine is a specialized method capable of pausing its execution (yield) to return control to Unity's game loop, resuming in subsequent frames exactly where it left off.
// A coroutine spanning across time
IEnumerator FadeRoutine() {
// Wait until the next frame
yield return null;
}
This mechanism allows writing multi-second animations or sequential events cleanly without cluttering Update with timer state machines.
Coroutine use cases
Coroutines are ideal for in-game delays and time-spread actions. Fading a character out gradually, spawning enemy waves every 3 seconds, or weapon reloading are cleanly scripted using coroutines.
// Countdown timer coroutine structure
IEnumerator Countdown() {
// Progressive steps over time
yield return null;
}
Because operations read as sequential steps in code, maintainability is significantly enhanced.
Exercise Print Coroutine profile
Assign "Coroutine" to routineType and "Pausable" to execution. Print Type: Coroutine | Execution: Pausable to the console.
Show example solution
using System;
class Program
{
static void Main()
{
string routineType = "Coroutine";
string execution = "Pausable";
Console.WriteLine("Type: " + routineType + " | Execution: " + execution);
}
}
Test yourself
-
What is the most distinct difference between a standard C# function and a Coroutine?
- Coroutines only running on the GPU via C++
- Standard functions waiting across an unlimited number of frames
- A Coroutine being able to pause execution and resume in later frames
- Coroutines never accepting variables or parameters
Show answer
A Coroutine being able to pause execution and resume in later frames — A Coroutine can pause its execution with a yield statement and resume from that exact line in future frames.
-
Complete coroutine method signature
____ SpawnWave()
Show answer
IEnumerator SpawnWave()
-
Coroutine core concepts
- Coroutine
- Pausable method across frames
- yield
- Yield execution to Unity temporarily
- Update()
- Loop runs each frame nonstop
- Fade Effect
- Coroutine-driven smooth fade
Next lesson: IEnumerator and yield