Course contentsShow
← Unity Game Development
Lesson 173 of 8283. Physics and InteractionFree lesson

Handling Input via C# Action Callbacks

Write event-driven scripts that respond asynchronously to input actions, decoupling player movement logic from the frame-by-frame update loop.

In this lesson, you will learn how to decouple your player movement from the Update loop by using C# action callbacks to respond to input events only when they happen.

Beyond the Frame-by-Frame Update

In earlier lessons, we used Input.GetKey or Input.GetAxis inside the Update method. While simple, this forces your script to constantly "poll" the input every single frame, even when the player isn't pressing anything. By using the New Input System’s Action Callbacks, we switch to an event-driven model. Instead of asking "Is the button pressed?" 60 times a second, the Input System tells our script "The button was pressed!" exactly when it happens.

Implementing C# Action Callbacks

To use callbacks, you assign a method to the performed event of an InputAction. When the action triggers, your assigned method executes immediately. This keeps your code clean and performance-efficient because the logic only runs when there is an actual input change.

Here is how you wire up a jump action using a callback:

using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerJump : MonoBehaviour
{
    public InputAction jumpAction;

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

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

    private void OnJumpTriggered(InputAction.CallbackContext context)
    {
        // This logic runs only when the jump button is pressed
        Debug.Log("Jump event received!");
    }
}

Why This Matters

By shifting to callbacks, your movement logic becomes modular and decoupled. You no longer need to worry about complex if statements inside Update. If you want to change how the jump behaves, you simply modify the OnJumpTriggered method. Furthermore, since the input is processed independently of the Update loop, your game logic remains responsive even if the frame rate fluctuates. This approach ensures your input handling is as robust as the physics-based systems we built in earlier modules.

Key Takeaway: Using C# action callbacks allows your game to react to inputs via event triggers rather than constant polling, resulting in cleaner, more efficient, and decoupled code.