0
0
UnityHow-ToBeginner ยท 3 min read

How to Use WaitForSeconds in Unity: Simple Guide

In Unity, WaitForSeconds is used inside a coroutine to pause execution for a specified number of seconds. You create a coroutine method with IEnumerator, use yield return new WaitForSeconds(seconds) to wait, and start it with StartCoroutine.
๐Ÿ“

Syntax

The basic syntax to use WaitForSeconds is inside a coroutine method. You write a method that returns IEnumerator, then use yield return new WaitForSeconds(seconds) where seconds is the wait time in seconds.

Finally, start the coroutine using StartCoroutine(MethodName()).

csharp
IEnumerator ExampleCoroutine()
{
    // Wait for 2 seconds
    yield return new WaitForSeconds(2f);
    // Code here runs after the wait
}
๐Ÿ’ป

Example

This example shows a Unity script that prints a message, waits 3 seconds, then prints another message. It demonstrates how WaitForSeconds pauses the coroutine without freezing the whole game.

csharp
using UnityEngine;
using System.Collections;

public class WaitExample : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(WaitAndPrint());
    }

    IEnumerator WaitAndPrint()
    {
        Debug.Log("Start waiting...");
        yield return new WaitForSeconds(3f);
        Debug.Log("3 seconds passed!");
    }
}
Output
Console Output: Start waiting... (3 seconds pause) 3 seconds passed!
โš ๏ธ

Common Pitfalls

  • Not using a coroutine: WaitForSeconds only works inside coroutines, not in regular methods.
  • Forgetting to start the coroutine: You must call StartCoroutine() to run the coroutine.
  • Using WaitForSeconds in Update: This won't work because Update is not a coroutine.
  • Expecting exact timing: The wait time is approximate and depends on frame rate.
csharp
/* Wrong way - does nothing */
IEnumerator Update()
{
    yield return new WaitForSeconds(1f); // Corrected: Update must be IEnumerator to use yield
}

/* Right way */
void Start()
{
    StartCoroutine(WaitInCoroutine());
}

IEnumerator WaitInCoroutine()
{
    yield return new WaitForSeconds(1f);
    Debug.Log("Waited 1 second");
}
๐Ÿ“Š

Quick Reference

WaitForSeconds Cheat Sheet:

UsageDescription
IEnumerator Method()Define a coroutine method
yield return new WaitForSeconds(seconds);Pause coroutine for given seconds
StartCoroutine(Method());Start the coroutine
Works only inside coroutinesCannot be used in normal methods
Wait time is approximateDepends on frame updates
โœ…

Key Takeaways

Use WaitForSeconds inside coroutines to pause execution without freezing the game.
Always start coroutines with StartCoroutine to run them.
WaitForSeconds only works in IEnumerator methods, not in Update or normal functions.
The wait time is approximate and depends on frame rate.
Use Debug.Log to see when the wait starts and ends during testing.