Triggering Actions via C# Event Callbacks
In this lesson, you will learn how to make your game react instantly to player input by connecting your Input Actions to C# methods using event callbacks.
Why use Callbacks?
Previously, you learned how to check for input inside the Update method by asking, "Is the button pressed?" every single frame. This is called polling. While simple, it can be inefficient. Event Callbacks allow you to "subscribe" to an action. Instead of constantly asking if a button was pressed, your script stays silent until the Input System sends a signal to your method automatically. This keeps your code clean and performance-friendly.
Implementing the Listener
When using the new Input System, each action has a set of events, such as performed, started, or canceled. To trigger code, you "subscribe" your method to these events using the += operator.
Here is how you wire up a simple "Jump" action:
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public InputAction jumpAction;
private void OnEnable()
{
// Enable the action so it can listen
jumpAction.Enable();
// Subscribe the Jump method to the 'performed' event
jumpAction.performed += Jump;
}
private void OnDisable()
{
// Always unsubscribe to prevent memory leaks or errors
jumpAction.performed -= Jump;
}
private void Jump(InputAction.CallbackContext context)
{
Debug.Log("Player Jumped!");
// Your jump logic goes here
}
}
Breaking it Down
InputAction.CallbackContext: When the event fires, the Input System sends a "context" object. This carries data about the interaction, such as how long a button was held or the magnitude of a joystick tilt.- Subscription (
+=): This tells Unity: "Whenever this action is performed, run theJumpmethod." - Unsubscription (
-=): When your object is disabled or destroyed, you must unsubscribe. Think of this like hanging up a phone; if you don't, your script will keep trying to "jump" even when the player is no longer in the game!
Key Takeaway: Event callbacks allow your game logic to react immediately to input by subscribing methods to action events, replacing the need to constantly poll for changes in the Update loop.