Pausing Execution with WaitForSeconds
In this lesson, you will learn how to inject precise timing delays into your game logic by pausing coroutine execution using WaitForSeconds.
Why We Need to Wait
In programming, code usually executes line-by-line as fast as the computer can process it. However, games often require "dramatic timing"—like waiting for an explosion animation to finish before destroying an object, or pausing for two seconds before a boss enemy performs its next attack. While a simple Update loop runs every single frame, a Coroutine allows us to "pause" our logic mid-method and resume it later.
Implementing the Delay
To pause a Coroutine, we use the yield return statement combined with a new instance of WaitForSeconds. When the execution reaches this line, the Coroutine will suspend its work, return control to Unity, and wait for the specified amount of time (in seconds) to pass before resuming on the next line.
Here is a basic example of how to implement this:
using UnityEngine;
using System.Collections;
public class DelayExample : MonoBehaviour
{
void Start()
{
StartCoroutine(DelayedMessage());
}
IEnumerator DelayedMessage()
{
Debug.Log("Waiting for 3 seconds...");
// This pauses the execution of this specific method
yield return new WaitForSeconds(3.0f);
Debug.Log("Time is up! This message appeared after the delay.");
}
}
How it Works
When you call yield return new WaitForSeconds(3.0f), you are telling Unity: "Stop running this script here, let the rest of the game keep updating, and come back to this line in exactly three seconds."
Because this is a Coroutine, the rest of your game remains fully functional while this timer counts down. You aren't freezing the entire game; you are simply placing one specific piece of logic on "pause" until the timer expires. This is an essential tool for managing event sequences, UI transitions, or periodic status updates without cluttering your Update loop with complex timers or frame-counting variables.
Key Takeaway: Use yield return new WaitForSeconds(n) to pause your Coroutine’s execution for a specific duration, allowing you to sequence game events without blocking the main game loop.