Coroutine chaining helps you run tasks one after another without freezing your game. It makes your game smooth and easy to follow.
Coroutine chaining in Unity
using System.Collections; using UnityEngine; public class CoroutineChainExample : MonoBehaviour { void Start() { StartCoroutine(FirstCoroutine()); } IEnumerator FirstCoroutine() { // Do something yield return new WaitForSeconds(1f); // Start next coroutine and wait for it to finish yield return StartCoroutine(SecondCoroutine()); // Continue after second coroutine finishes Debug.Log("All coroutines finished."); } IEnumerator SecondCoroutine() { // Do something else yield return new WaitForSeconds(2f); } }
You use yield return StartCoroutine(OtherCoroutine()) to wait for another coroutine to finish.
Coroutines run over multiple frames without freezing the game.
IEnumerator EmptyCoroutine()
{
// No yield, runs instantly
yield break;
}IEnumerator SingleStepCoroutine()
{
Debug.Log("Step 1");
yield return null; // Wait one frame
Debug.Log("Step 2");
}IEnumerator ChainExample()
{
Debug.Log("Start first");
yield return StartCoroutine(WaitAndPrint(1f, "First done"));
Debug.Log("Start second");
yield return StartCoroutine(WaitAndPrint(2f, "Second done"));
Debug.Log("Chain complete");
}
IEnumerator WaitAndPrint(float waitTime, string message)
{
yield return new WaitForSeconds(waitTime);
Debug.Log(message);
}This program starts a coroutine chain where the first task waits 1 second, then starts the second task which waits 2 seconds. Messages show the order clearly.
using System.Collections; using UnityEngine; public class CoroutineChainDemo : MonoBehaviour { void Start() { Debug.Log("Starting coroutine chain..."); StartCoroutine(FirstTask()); } IEnumerator FirstTask() { Debug.Log("First task started"); yield return new WaitForSeconds(1f); Debug.Log("First task finished, starting second task"); yield return StartCoroutine(SecondTask()); Debug.Log("All tasks completed"); } IEnumerator SecondTask() { Debug.Log("Second task started"); yield return new WaitForSeconds(2f); Debug.Log("Second task finished"); } }
Time complexity depends on the wait times and tasks inside coroutines, but chaining itself is simple and fast.
Space complexity is low; coroutines use little memory while waiting.
Common mistake: forgetting to yield return the chained coroutine, which causes tasks to run at the same time instead of in order.
Use coroutine chaining when you want tasks to happen one after another without blocking the game. Use parallel coroutines if tasks can run together.
Coroutine chaining lets you run tasks one after another smoothly.
Use yield return StartCoroutine() to wait for the next task.
This helps keep your game responsive and organized.