0
0
Unityframework~5 mins

WaitForSeconds and WaitForEndOfFrame in Unity

Choose your learning style9 modes available
Introduction

These help you pause actions in your game for a short time or until the frame finishes. This makes your game feel smooth and timed right.

You want to wait a few seconds before showing a message or changing a scene.
You need to delay an action without freezing the whole game.
You want to run code right after the current frame finishes drawing.
You want to create smooth animations or timed effects.
You want to wait between repeated actions in a game loop.
Syntax
Unity
yield return new WaitForSeconds(seconds);
yield return new WaitForEndOfFrame();

Both are used inside a coroutine, which is a special function that can pause and resume.

WaitForSeconds pauses for a set time; WaitForEndOfFrame waits until the frame is fully drawn.

Examples
This waits 2 seconds before printing the second message.
Unity
IEnumerator ExampleWaitSeconds() {
    Debug.Log("Start waiting...");
    yield return new WaitForSeconds(2f);
    Debug.Log("2 seconds passed!");
}
This runs code right after the current frame finishes drawing.
Unity
IEnumerator ExampleWaitEndOfFrame() {
    Debug.Log("Before frame ends");
    yield return new WaitForEndOfFrame();
    Debug.Log("After frame ends");
}
Sample Program

This script waits 3 seconds, prints a message, then waits until the frame ends and prints another message.

Unity
using UnityEngine;
using System.Collections;

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

    IEnumerator WaitAndPrint() {
        Debug.Log("Waiting for 3 seconds...");
        yield return new WaitForSeconds(3f);
        Debug.Log("3 seconds passed!");

        Debug.Log("Waiting for end of frame...");
        yield return new WaitForEndOfFrame();
        Debug.Log("Frame ended!");
    }
}
OutputSuccess
Important Notes

Coroutines must be started with StartCoroutine to work.

WaitForSeconds uses game time, so it pauses even if the frame rate changes.

WaitForEndOfFrame is useful for things like taking screenshots or updating UI after rendering.

Summary

Use WaitForSeconds to pause for a set time inside coroutines.

Use WaitForEndOfFrame to run code after the current frame finishes drawing.

Both help make timed and smooth actions in your Unity game.