VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/coroutines-in-unity/

⇱ Coroutines In Unity - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Coroutines In Unity

Last Updated : 4 May, 2026

Coroutines in Unity are used to execute code over time instead of all at once, making them ideal for handling delays, animations, and asynchronous tasks without freezing the game. Unlike normal methods that run completely in one frame, coroutines can spread work over multiple frames.

  • Runs alongside normal game code
  • Can wait for seconds, frames, or conditions
  • Does NOT freeze the game while waiting

Creating a Simple Coroutine

A coroutine returns enumerate and uses yield return to pause.

Output:

👁 Coroutines-In-Unity
Coroutines In Unity

StartCoroutine() begins the coroutine. yield return new WaitForSeconds(2f) pauses it for 2 seconds. The game continues running normally during the wait.

Common Yield Instructions

InstructionWaits for
yield return nullOne frame
yield return new WaitForSeconds(2f)2 seconds
yield return new WaitForSecondsRealtime(2f)2 seconds (ignores timeScale)
yield return new WaitForFixedUpdate()Next physics frame
yield return new WaitUntil(() => condition)Until condition is true
yield return new WaitWhile(() => condition)While condition is true
yield return StartCoroutine(Another())Another coroutine to finish

Example: Spawning Enemies Every 3 Seconds

Output:

👁 Spawning-Enemies-Using-Coroutine-In-Unity
Spawning Enemies Using Coroutine In Unity

The while loop runs forever. After each spawn, it waits 3 seconds before spawning again.

Stopping Coroutines

Save the coroutine reference to stop it later. StopAllCoroutines() stops every coroutine on the script.

Coroutine vs Invoke vs Update Timer

  • Coroutine: Complex timing, waiting conditions, smooth transitions.
  • Invoke: Simple one-time delay.
  • Update timer: Frame-by-frame counting.
Comment
Article Tags:
Article Tags:

Explore