In this lesson, you will learn how to trigger game events after a specific delay using Coroutines to ensure your timing remains precise regardless of frame rate fluctuations.
Why standard timers struggle
When you try to time events by counting frames—for example, waiting for 60 frames to pass—you run into a major issue: frame rate variability. If a player’s computer lags, 60 frames might take a whole second to process; on a high-end machine, it might take a fraction of a second. This makes your game feel inconsistent. To solve this, we use Coroutines combined with WaitForSeconds.
Using Coroutines for Timing
A Coroutine is a special type of method that can "pause" its execution and return control to Unity, then pick up exactly where it left off later. When you use yield return new WaitForSeconds(time), you are telling Unity to pause the method for a specific number of seconds in real-time, completely ignoring how many frames have passed in the meantime.
Here is how you can implement a simple timed message:
using UnityEngine;
using System.Collections;
public class TimedEventExample : MonoBehaviour
{
void Start()
{
// Start the Coroutine
StartCoroutine(DelayedMessage());
}
IEnumerator DelayedMessage()
{
Debug.Log("Waiting...");
// Wait for exactly 2 seconds of real-time
yield return new WaitForSeconds(2.0f);
Debug.Log("Two seconds have passed!");
}
}
Why this is better
By using WaitForSeconds, the timing is calculated based on Unity’s internal clock rather than the frame cycle. Even if the game freezes for a moment or the frame rate drops significantly, the Coroutine will wait for the exact real-world time requested. This ensures that mechanics—like a buff expiring, an enemy spawning, or a light switching off—happen predictably for every player, regardless of their hardware performance.
Key Takeaway: Use Coroutines with WaitForSeconds to execute logic after a specific duration, ensuring your game timing remains accurate and consistent regardless of how fast or slow the game is running.