0
0
Unityframework~3 mins

Why Coroutine basics (IEnumerator) in Unity? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could pause actions in your game without stopping everything else?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
void Update() {
  if (waiting) {
    timer += Time.deltaTime;
    if (timer >= 3) {
      Jump();
      waiting = false;
    }
  }
}

void StartWaiting() {
  waiting = true;
  timer = 0;
}
After
IEnumerator WaitAndJump() {
  yield return new WaitForSeconds(3);
  Jump();
}

void StartWaiting() {
  StartCoroutine(WaitAndJump());
}
What It Enables

Coroutines enable smooth, readable, and efficient timed actions in your game without freezing or complex timer code.

Real Life Example

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.

Key Takeaways

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.