0
0
UnityConceptBeginner · 3 min read

What Is Coroutine in Unity: Simple Explanation and Example

In Unity, a coroutine is a special function that allows you to pause execution and resume it later, letting you run tasks over multiple frames without freezing the game. It helps manage time-based actions like waiting or animations smoothly inside your game loop.
⚙️

How It Works

Think of a coroutine like a bookmark in a book. When you reach a point where you want to pause reading and come back later, you place a bookmark. In Unity, a coroutine pauses its work at certain points and resumes from there in the next frame or after a delay. This lets your game keep running smoothly without waiting for the whole task to finish.

Under the hood, Unity runs coroutines alongside the main game loop. When a coroutine hits a yield statement, it pauses and tells Unity when to continue. This way, you can spread out work over time, like waiting for 3 seconds or waiting until a condition is true, without stopping the game.

💻

Example

This example shows a coroutine that waits for 2 seconds before printing a message. It demonstrates how to start a coroutine and use yield return new WaitForSeconds() to pause.

csharp
using UnityEngine;
using System.Collections;

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

    IEnumerator WaitAndPrint()
    {
        Debug.Log("Coroutine started");
        yield return new WaitForSeconds(2f);
        Debug.Log("2 seconds passed");
    }
}
Output
Coroutine started 2 seconds passed
🎯

When to Use

Use coroutines when you want to perform actions over time without freezing your game. For example:

  • Waiting for a few seconds before triggering an event.
  • Animating objects smoothly frame by frame.
  • Loading resources asynchronously.
  • Creating timed sequences like countdowns or delays.

Coroutines are perfect for tasks that need to pause and resume without blocking the main game flow.

Key Points

  • Coroutines run alongside the main game loop and can pause execution.
  • They use yield to wait for time or conditions.
  • Start coroutines with StartCoroutine().
  • They help keep your game responsive during delays or animations.

Key Takeaways

Coroutines let you pause and resume code without freezing the game.
Use yield return to wait inside coroutines.
Start coroutines with StartCoroutine() in Unity.
Ideal for timed actions, animations, and asynchronous tasks.
They keep your game smooth by spreading work over multiple frames.