0
0
UnityHow-ToBeginner ยท 4 min read

How to Use Coroutine in Unity: Simple Guide with Examples

In Unity, use Coroutine to run code over multiple frames without blocking the game. Start a coroutine by calling StartCoroutine with an IEnumerator method that uses yield return to pause execution.
๐Ÿ“

Syntax

A coroutine in Unity is a method that returns IEnumerator. You start it using StartCoroutine. Inside the coroutine, use yield return to wait for a condition or time before continuing.

  • IEnumerator Method: Defines the coroutine steps.
  • yield return: Pauses execution and resumes later.
  • StartCoroutine: Begins running the coroutine.
csharp
private IEnumerator MyCoroutine()
{
    // Code before waiting
    yield return new WaitForSeconds(2f); // Wait 2 seconds
    // Code after waiting
}

void Start()
{
    StartCoroutine(MyCoroutine());
}
๐Ÿ’ป

Example

This example shows a coroutine that prints messages before and after a 3-second wait. It demonstrates how the game continues running while waiting.

csharp
using UnityEngine;
using System.Collections;

public class CoroutineExample : MonoBehaviour
{
    private IEnumerator PrintMessages()
    {
        Debug.Log("Start waiting...");
        yield return new WaitForSeconds(3f); // Wait for 3 seconds
        Debug.Log("3 seconds passed!");
    }

    void Start()
    {
        StartCoroutine(PrintMessages());
    }
}
Output
Start waiting... 3 seconds passed!
โš ๏ธ

Common Pitfalls

Common mistakes when using coroutines include:

  • Not using StartCoroutine to run the coroutine method, which means it won't execute.
  • Using yield return null incorrectly, which only waits one frame.
  • Stopping coroutines unintentionally or forgetting to stop them when needed.
  • Trying to return values directly from coroutines (they can't return values like normal methods).
csharp
/* Wrong way: calling coroutine method without StartCoroutine */
void Start()
{
    PrintMessages(); // This does NOT start the coroutine properly
}

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

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

Quick Reference

ConceptDescription
IEnumerator MethodDefines coroutine steps with yield returns
StartCoroutineStarts running the coroutine
yield return nullWaits one frame before continuing
yield return new WaitForSeconds(seconds)Waits specified seconds
StopCoroutineStops a running coroutine
โœ…

Key Takeaways

Use IEnumerator methods with yield return to create coroutines in Unity.
Always start coroutines with StartCoroutine to run them properly.
yield return pauses coroutine execution without freezing the game.
Coroutines cannot return values like normal functions.
Remember to stop coroutines if you no longer need them to avoid unwanted behavior.