Consider this Unity Coroutine code snippet. What will be printed to the console?
IEnumerator PrintNumbers()
{
Debug.Log("Start");
yield return new WaitForSeconds(1);
Debug.Log("Middle");
yield return new WaitForSeconds(1);
Debug.Log("End");
}
// Assume this Coroutine is started once at time 0.Remember that yield return new WaitForSeconds(1) pauses the Coroutine for 1 second before continuing.
The Coroutine prints "Start" immediately, then waits 1 second before printing "Middle", then waits another second before printing "End".
In Unity, if you start a Coroutine and then call StopCoroutine on it before it finishes, what will happen?
Think about what stopping a Coroutine means in Unity.
Calling StopCoroutine immediately halts the Coroutine. No further code inside it will execute.
Look at this Coroutine code. It never prints "Done". Why?
IEnumerator WaitAndPrint()
{
yield return new WaitForSeconds(2);
yield return null;
Debug.Log("Done");
}
// Coroutine started once.Think about what yield return null does in a Coroutine.
yield return null waits one frame, then continues. So "Done" will print after 2 seconds plus one frame.
Which of these method signatures is valid for a Coroutine in Unity?
Remember that Coroutines must return IEnumerator.
Coroutines in Unity must return IEnumerator. Other return types are invalid for Coroutines.
Consider this Coroutine that prints "Tick" every 0.5 seconds for 3 seconds total. How many times will "Tick" print?
IEnumerator TickCoroutine()
{
float elapsed = 0f;
while (elapsed < 3f)
{
Debug.Log("Tick");
yield return new WaitForSeconds(0.5f);
elapsed += 0.5f;
}
}
// Coroutine started once.Count how many 0.5 second intervals fit into 3 seconds.
The loop runs while elapsed is less than 3. It increments elapsed by 0.5 each time, so it runs 6 times, printing "Tick" each time.