In this lesson, you will learn how to create non-blocking, time-delayed logic by implementing the IEnumerator interface and the yield return statement.
The Problem with Standard Methods
In C#, when you call a standard method, it runs from start to finish within a single frame. If you want a sequence of events to happen over several frames—like waiting three seconds before spawning an enemy or fading an object’s transparency—you usually have to write complex logic inside Update. This makes your code messy and difficult to track.
The Coroutine Solution
Coroutines allow you to pause the execution of a method and return control to Unity, then resume exactly where you left off in a later frame. To do this, your method must return an IEnumerator and include at least one yield return statement.
The yield return keyword tells Unity: "Pause this method right here, go do other game work, and come back to this line when the specified condition is met."
Implementing Your First Coroutine
Here is a simple example that prints a message, waits for one second, and then prints another:
using UnityEngine;
using System.Collections;
public class CoroutineExample : MonoBehaviour
{
void Start()
{
// To start a coroutine, use the StartCoroutine method
StartCoroutine(MyRoutine());
}
IEnumerator MyRoutine()
{
Debug.Log("Task started.");
// Pause execution for 1 second
yield return new WaitForSeconds(1.0f);
Debug.Log("Task finished after 1 second!");
}
}
Why Use IEnumerator?
By using the IEnumerator interface, you allow the method to behave like a state machine. Instead of the entire function finishing instantly, it breaks into segments. When you yield return, you are essentially handing a "bookmark" back to Unity. When the condition (like one second passing) is met, Unity uses that bookmark to resume your code right on the next line. This approach keeps your logic clean, readable, and perfectly suited for timed sequences without impacting the performance of your Update loop.
Key Takeaway: Coroutines allow you to pause method execution across multiple frames using yield return, enabling clean and efficient handling of time-based sequences.