What if you could pause actions in your game without stopping everything else?
Why Coroutine basics (IEnumerator) in Unity? - Purpose & Use Cases
Imagine you want your game character to wait for 3 seconds before jumping, but you also want the game to keep running smoothly during that wait.
If you try to pause the whole game manually, everything freezes and feels stuck.
Using a simple pause or delay stops the entire game, making it unresponsive and frustrating for players.
Manually checking timers every frame is messy and hard to manage, especially when you have many timed actions.
Coroutines let you write waiting code that pauses only the specific action, while the rest of the game keeps running.
Using IEnumerator, you can easily create sequences that wait, repeat, or delay without freezing the game.
void Update() {
if (waiting) {
timer += Time.deltaTime;
if (timer >= 3) {
Jump();
waiting = false;
}
}
}
void StartWaiting() {
waiting = true;
timer = 0;
}IEnumerator WaitAndJump() {
yield return new WaitForSeconds(3);
Jump();
}
void StartWaiting() {
StartCoroutine(WaitAndJump());
}Coroutines enable smooth, readable, and efficient timed actions in your game without freezing or complex timer code.
In a game, you want an enemy to flash red for 2 seconds after being hit, then return to normal color, all while the game continues running.
Manual waiting freezes the whole game and is hard to manage.
Coroutines pause only specific actions, keeping the game smooth.
Using IEnumerator makes timed sequences simple and clean.