Course contentsShow
← Unity Game Development
Lesson 136 of 8282. Scripting and LifecycleFree lesson

Waiting for Input Events in Coroutines

Design interactive gameplay sequences that pause execution until the player provides specific input or triggers a designated game event.

In this lesson, you will learn how to pause your game logic within a coroutine until a player performs a specific action, such as pressing a key or clicking a button.

Why Pause Execution?

In game design, we often need to build "gated" sequences—situations where the game cannot proceed until the player interacts with the world. For instance, you might display a tutorial message and wait for the player to press "Space" before spawning the first enemy. While you could use Update() with a boolean flag, using a coroutine allows you to write this sequence linearly, making your code much easier to read and maintain.

The Logic of Waiting

To wait for input inside a coroutine, we use a while loop combined with a yield return null; statement. This tells Unity to "pause here and resume in the next frame" as long as the condition (the player’s input) has not been met.

Consider this example where we wait for a specific key press:

IEnumerator TutorialSequence()
{
    Debug.Log("Press Space to continue...");

    // This loop keeps the coroutine waiting one frame at a time
    // as long as the Space key is NOT pressed.
    while (!Input.GetKeyDown(KeyCode.Space))
    {
        yield return null; 
    }

    Debug.Log("Input detected! Proceeding to the next task.");
}

How it Works

  1. The Loop: When the code execution enters the while block, it checks for your condition.
  2. The Yield: If the player hasn't pressed the key yet, yield return null hands control back to Unity, allowing the rest of the game to continue running (animations, physics, etc.).
  3. The Resume: On the next frame, the coroutine wakes up and checks the condition again.
  4. The Break: The moment Input.GetKeyDown returns true, the while loop finishes, and the coroutine proceeds to the next lines of code.

This approach is highly efficient because it keeps your logic contained within a single method rather than scattering it across multiple Update calls.

Key Takeaway: Use a while loop with yield return null inside a coroutine to pause execution until a specific input condition is met, keeping your linear gameplay logic clean and organized.