In this lesson, you will learn how to create and swap between different "Input Action Maps" to ensure your player’s buttons perform the right actions depending on whether they are walking, driving, or navigating a menu.
The Concept of Context
In a game, the same button might need to do two completely different things. For example, the Space key might make your character jump while they are on foot, but that same key should make your car accelerate while driving. Instead of writing messy if statements to check if the player is in a vehicle, we use Action Maps.
Action Maps allow you to group related inputs together. You can create a "Player" map for walking and a "Vehicle" map for driving. Unity’s Input System lets you enable only the map you currently need, effectively muting the others.
Switching Maps at Runtime
To handle this, you define your maps in the Input Actions asset. Once defined, you can switch between them using C# in your scripts. When you enable one map, you should disable the others to prevent input conflicts.
Here is a simplified example of how you toggle these contexts:
public void SwitchToDriving()
{
// Disable the walking inputs
playerInput.actions.FindActionMap("Player").Disable();
// Enable the driving inputs
playerInput.actions.FindActionMap("Vehicle").Enable();
}
public void SwitchToWalking()
{
// Disable driving, re-enable walking
playerInput.actions.FindActionMap("Vehicle").Disable();
playerInput.actions.FindActionMap("Player").Enable();
}
Why This Matters
By compartmentalizing your inputs, you avoid "input bleeding," where a button press triggers an unintended action because the game didn't know the player had entered a vehicle. This makes your code cleaner, easier to debug, and much more modular. If you decide to add a new "Menu" map later, you simply create the map in your asset and swap to it using the exact same logic, without ever touching your movement scripts.
Key Takeaway: Use multiple Action Maps to group context-specific controls, enabling and disabling them at runtime to ensure your buttons only trigger the actions relevant to the player's current state.