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

Implementing Player Input Component for Event Handling

Attach the Player Input component to game objects to automatically route input signals to specific C# event methods.

In this lesson, you will learn how to use the Player Input component to bridge the gap between your input configuration and your C# scripts using event-based communication.

Up until now, you have defined your Input Action assets and mapped them to physical buttons. To make these inputs actually do something in your game, you need to "listen" for these signals. While you could poll for input every frame in Update(), the Player Input component offers a more elegant solution: Invoke Unity Events.

Configuring the Component

When you select your game object with a Player Input component, locate the Behavior dropdown in the Inspector and set it to Invoke Unity Events. This setting reveals a list of your Action Maps. By expanding these, you will see a list of your defined actions (like "Jump" or "Move") with an empty "Event" slot.

This slot acts as a bridge. You can drag a script component into this field and select a specific method to run whenever that action is triggered.

Writing the Event Method

To use this system, your script must contain a public method that accepts an InputAction.CallbackContext parameter. This parameter acts as a data package containing information about the input (such as whether it was pressed, released, or the specific value of an axis).

Here is a simple example for a jump action:

using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{
    public void OnJump(InputAction.CallbackContext context)
    {
        // Check if the button was just pressed
        if (context.started)
        {
            Debug.Log("Jump action received!");
            // Trigger your physics-based jump logic here
        }
    }
}

By connecting your method in the Inspector, the Player Input component handles the routing automatically. Whenever the user hits the Jump key, Unity triggers your OnJump method, keeping your input logic decoupled from your main loop. This makes your code cleaner, easier to debug, and highly responsive to user interaction.

Key Takeaway: The Player Input component’s "Invoke Unity Events" mode allows you to route input signals directly to public C# methods, creating a clean, event-driven connection between player actions and your physics logic.