What is a Coroutine?
- Game Development course
- Intermediate
- Lesson 43/83
- 4 min
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.
Practice Print Coroutine profile
Assign "Coroutine" to routineType and "Pausable" to execution. Print Type: Coroutine | Execution: Pausable to the console.
Starter code
using System;
class Program
{
static void Main()
{
// routineType ve execution değerlerini tanımlayıp yazdır
}
}Sample solution
using System;
class Program
{
static void Main()
{
string routineType = "Coroutine";
string execution = "Pausable";
Console.WriteLine("Type: " + routineType + " | Execution: " + execution);
}
}Expected output
Type: Coroutine | Execution: Pausable
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
- Coroutines never accepting variables or parameters
Explanation: A Coroutine can pause its execution with a yield statement and resume from that exact line in future frames.
2 Complete coroutine method signature
____ SpawnWave()
IEnumerator SpawnWave()
Explanation: To define a coroutine in Unity, the method return type is declared as IEnumerator.
3 Coroutine core concepts
| Term | Meaning |
|---|---|
Coroutine |
Pausable method across frames |
yield |
Yield execution to Unity temporarily |
Update() |
Loop runs each frame nonstop |
Fade Effect |
Coroutine-driven smooth fade |