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
IEnumeratoras the return type for the coroutine method. - Calling
StartCoroutinewithout parentheses, which passes the method itself instead of starting it. - Trying to use
yield returnin 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 returnto 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.