IEnumerator PrintNumbers()
{
Debug.Log("Start");
yield return new WaitForSeconds(1f);
Debug.Log("One second passed");
yield return new WaitForSeconds(2f);
Debug.Log("Three seconds passed");
}
// Assume this coroutine is started at time 0The coroutine prints "Start" immediately. Then it waits 1 second before printing "One second passed". After that, it waits 2 more seconds before printing "Three seconds passed". So the total time before the last message is 3 seconds.
Coroutines let you pause execution at certain points without freezing the game. This keeps the game responsive and smooth, unlike loops that block the main thread.
IEnumerator FlashLight()
{
while(true)
{
light.enabled = true;
yield return new WaitForSeconds(0.5f);
light.enabled = false;
yield return new WaitForSeconds(0.5f);
}
}
// Assume 'light' is a valid Light componentThe coroutine uses an infinite loop with yield return WaitForSeconds to toggle the light on and off every 0.5 seconds. This is a common and correct pattern in Unity.
In Unity C#, you must create a new WaitForSeconds object with 'new' and specify the time as a float with 'f'. The yield return statement requires the new object.
bool isReady = false; IEnumerator WaitForReady() { // Fill in the waiting logic here Debug.Log("Ready!"); }
All three options correctly pause the coroutine until 'isReady' is true. 'yield return null' waits one frame, so looping while !isReady works. 'WaitUntil' waits until the condition is true. 'WaitWhile' waits while the condition is true, so waiting while !isReady is true also works.