In this lesson, you will learn how to trigger game logic precisely after Unity has finished rendering the current frame to the screen.
The "End of Frame" Timing
Usually, when you write code in Update, it runs before the engine renders the frame. However, there are times—such as capturing a screenshot or performing a cleanup operation that relies on the finalized visual state—where you need to wait until the GPU has finished drawing everything.
Unity provides a specific yield instruction called WaitForEndOfFrame for this purpose. When you use this inside a coroutine, the execution pauses right after the camera has finished drawing the frame but before the frame is presented to the screen.
Practical Example: Taking a Screenshot
A classic use case for WaitForEndOfFrame is capturing a screenshot. If you try to capture the screen during the normal Update loop, the frame might still be in the process of being drawn, leading to missing UI elements or artifacts. By using this instruction, you guarantee the frame is perfectly rendered.
using UnityEngine;
using System.Collections;
public class ScreenshotManager : MonoBehaviour
{
public void CaptureScreen()
{
StartCoroutine(CaptureRoutine());
}
private IEnumerator CaptureRoutine()
{
// Wait until the end of the current rendering cycle
yield return new WaitForEndOfFrame();
// Now it is safe to capture the rendered frame
Texture2D texture = ScreenCapture.CaptureScreenshotAsTexture();
Debug.Log("Screenshot captured at end of frame!");
}
}
Why this matters
Using WaitForEndOfFrame is essential when your logic requires a "finished" product. If you are cleaning up temporary render textures or resetting post-processing effects, waiting ensures the player never sees a "glitchy" frame where objects were halfway through being drawn. It acts as a safety barrier, ensuring your code synchronizes perfectly with the display output rather than the internal game loop calculations.
Key Takeaway: Use yield return new WaitForEndOfFrame() when you need to perform operations that depend on the final visual state of the rendered frame, such as screen captures or buffer resets.