Course contentsShow
← Unity Game Development
Lesson 58 of 8281. Unity FoundationsFree lesson

Implementing Event-Driven Input Handling

Learners will subscribe to input action events to execute code asynchronously when players perform specific actions like jumping or firing.

In this lesson, you will learn how to trigger game actions by "subscribing" to input events, allowing your code to react instantly whenever a player presses a button.

Moving Beyond Polling

Previously, you might have used "polling"—checking if (Input.GetKey(KeyCode.Space)) inside every single frame of the Update() method. While this works, it is inefficient because your script constantly asks, "Is the button pressed?" even when the player is idle.

Event-driven input changes this relationship. Instead of constantly checking, you register a "listener." You tell Unity: "When the 'Jump' action happens, run this specific method." Your code remains silent until that exact moment, making your game more performant and your scripts easier to read.

Subscribing to Actions

To use event-driven input with the New Input System, you subscribe to an action's performed event. Think of this like setting an alarm: you don't look at the clock every second; you just wait for the alarm to ring.

Here is how you wire up a method to a "Jump" action:

using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{
    public InputAction jumpAction;

    private void OnEnable()
    {
        // Subscribe to the performed event
        jumpAction.performed += OnJump;
        jumpAction.Enable();
    }

    private void OnDisable()
    {
        // Always unsubscribe to prevent memory leaks
        jumpAction.performed -= OnJump;
        jumpAction.Disable();
    }

    private void OnJump(InputAction.CallbackContext context)
    {
        Debug.Log("Jump action triggered!");
    }
}

Why this matters

When you use += on an event, you are adding your method to a list of "things to do" when the input occurs. By using OnEnable and OnDisable, you ensure your script is only listening while the object is active in the game world. This pattern decouples your logic—the code that handles jumping only runs when the jump event actually fires, rather than cluttering your Update() loop with constant input checks.

Key Takeaway: Event-driven input allows your scripts to remain idle until an input action triggers them, creating cleaner, more efficient code by subscribing methods to specific input events.