Implementing Coroutines for Time-Based Execution
In this lesson, you will learn how to pause and resume your code execution over several frames, allowing you to create timed events without freezing the game.
The Problem: Blocking the Thread
When you write code in Update, it runs every single frame. If you wanted to wait for two seconds before triggering an explosion, you might be tempted to use a loop to "wait." However, if you write code that tells the game to "wait" on the main thread, the entire game will freeze—it won't render graphics, process physics, or handle your input. This is where Coroutines come in.
The Solution: Coroutines
A Coroutine is a special type of method that allows you to pause its execution and return control to Unity, then pick up exactly where it left off later.
To use one, you define a method with the IEnumerator return type and use the yield return statement. Think of yield as a "pause button" that tells Unity: "I'm done for now, go handle other things (like rendering or input), and come back to this line in a few seconds."
Here is how you would trigger a timed message:
using UnityEngine;
using System.Collections;
public class TimerExample : MonoBehaviour
{
void Start()
{
// Start the Coroutine
StartCoroutine(WaitAndPrint());
}
IEnumerator WaitAndPrint()
{
Debug.Log("Waiting...");
// This pauses the method for 2 seconds without stopping the game
yield return new WaitForSeconds(2.0f);
Debug.Log("Time is up!");
}
}
Why it Works
When yield return new WaitForSeconds(2.0f) is reached, the Coroutine exits and yields control back to Unity. Unity continues running your game, checking input, and processing physics. After the timer elapses, Unity automatically resumes your WaitAndPrint method on the very next frame. This allows you to sequence complex events—like spawning waves of enemies, fading out UI elements, or triggering delayed sounds—without blocking the main game loop or requiring messy timer variables inside your Update method.
Key Takeaway: Coroutines allow your code to "pause" execution and wait for a specific duration while keeping the game running smoothly for the player.