In this lesson, you will learn how to decouple your game logic from specific hardware keys by organizing your controls into logical categories called Action Maps.
Why Decouple Input?
In the legacy Input Manager, you might have hardcoded a line like Input.GetKey(KeyCode.Space) inside your player movement script. This is problematic because if you want to change the jump button to a controller button later, you have to hunt through your code to update it.
The New Input System solves this by using Input Action Assets. These act as a middleman between the hardware (keyboard, mouse, gamepad) and your code.
Using Action Maps
An Action Map is essentially a "context" for your controls. Think of your game like a human: when you are walking, you need a "Player" map. When you are navigating a menu, you need a "UI" map. By splitting these, you ensure that pressing the "Escape" key doesn't make your character jump while you're trying to pause the game.
Within an Action Map, you define Actions (like "Jump" or "Move"). Instead of listening for a "Spacebar," your script simply asks, "Did the Jump action fire?"
The Workflow
- Create an Input Actions Asset: Right-click in your Project folder -> Create -> Input Actions.
- Define Maps: Inside the editor window, create a Map named
Player. - Create Actions: Under
Player, add an Action calledJump. - Bind Controls: Add bindings to your
Jumpaction. You can add one forSpaceon the Keyboard and another for theSouth Buttonon a Gamepad.
Your code no longer cares what pressed the button. It only cares that the Jump event was triggered.
// Example of checking an Action
void OnJump(InputAction.CallbackContext context) {
if (context.performed) {
// Logic for jumping goes here
}
}
By using Action Maps, your code becomes modular and hardware-agnostic, meaning your game is ready for any controller the player chooses to use.
Key Takeaway: Action Maps serve as a bridge that allows you to define logical gameplay inputs once, making your code cleaner and your game easier to rebind for different hardware.