0
0
UnityHow-ToBeginner ยท 4 min read

How to Use StartCoroutine in Unity: Simple Guide

In Unity, use StartCoroutine to run a method that pauses and resumes over time, typically returning IEnumerator. Call StartCoroutine with the coroutine method to execute it asynchronously alongside other code.
๐Ÿ“

Syntax

The basic syntax to start a coroutine is StartCoroutine(MethodName());. The method must return IEnumerator and use yield return to pause execution.

  • StartCoroutine: Unity method to begin the coroutine.
  • MethodName(): The coroutine method that returns IEnumerator.
  • yield return: Pauses the coroutine until the next frame or specified wait time.
csharp
StartCoroutine(MyCoroutine());

private IEnumerator MyCoroutine()
{
    // code before pause
    yield return new WaitForSeconds(1f); // pause for 1 second
    // code after pause
}
๐Ÿ’ป

Example

This example shows a coroutine that prints messages before and after a 2-second wait. It demonstrates how StartCoroutine runs the method asynchronously without freezing the game.

csharp
using UnityEngine;
using System.Collections;

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

    private IEnumerator PrintMessages()
    {
        Debug.Log("Message 1: Start");
        yield return new WaitForSeconds(2f); // wait 2 seconds
        Debug.Log("Message 2: After 2 seconds");
    }
}
Output
Console output: Message 1: Start (wait 2 seconds) Message 2: After 2 seconds
โš ๏ธ

Common Pitfalls

Common mistakes when using StartCoroutine include:

  • Not using IEnumerator as the return type for the coroutine method.
  • Calling StartCoroutine without parentheses, which passes the method itself instead of starting it.
  • Trying to use yield return in non-coroutine methods.
  • Forgetting that coroutines run asynchronously and do not block the main thread.
csharp
/* Wrong: Missing parentheses, does not start coroutine */
StartCoroutine(PrintMessages);

/* Correct: Include parentheses to start coroutine */
StartCoroutine(PrintMessages());

private IEnumerator PrintMessages()
{
    yield return null;
}
๐Ÿ“Š

Quick Reference

Remember these tips when using StartCoroutine:

  • Coroutine methods must return IEnumerator.
  • Use yield return to pause execution.
  • Call StartCoroutine(MethodName()); with parentheses.
  • Coroutines run alongside other code without freezing the game.
โœ…

Key Takeaways

Use StartCoroutine with a method that returns IEnumerator to run code over time.
Always include parentheses when calling StartCoroutine to start the coroutine.
Use yield return inside the coroutine to pause execution without freezing the game.
Coroutines run asynchronously alongside other game logic.
Common errors include missing IEnumerator return type and incorrect StartCoroutine calls.