In this lesson, you will learn how to switch between different control schemes, like walking and driving, by toggling Input Action Maps in Unity’s Input System.
Why Context Matters
When a player hops into a car, the button used to "jump" while on foot might suddenly need to be the "handbrake." Instead of writing complex if/else statements inside one massive script, we use Action Maps. An Action Map is a collection of related inputs. By swapping which map is "active," we ensure our scripts only listen to relevant controls for the player's current state.
Toggling Maps at Runtime
To implement this, you need a reference to your PlayerInput component. In your script, you can use the SwitchCurrentActionMap() method to swap control schemes instantly.
Imagine you have two Action Maps: one named "Player" and one named "Vehicle." You can switch between them like this:
using UnityEngine;
using UnityEngine.InputSystem;
public class InputSwitcher : MonoBehaviour
{
public PlayerInput playerInput;
public void EnterVehicle()
{
// Switch to vehicle controls
playerInput.SwitchCurrentActionMap("Vehicle");
}
public void ExitVehicle()
{
// Switch back to walking controls
playerInput.SwitchCurrentActionMap("Player");
}
}
Organizing Your Logic
By using this approach, you keep your code clean and decoupled. The script handling your "Walking" logic doesn't need to know the vehicle exists; it simply stops receiving inputs the moment you switch the active Action Map to "Vehicle."
When you define these maps in the Input Action Asset, make sure the names match exactly what you pass into the SwitchCurrentActionMap method. This simple switch ensures that your player’s "Jump" key doesn't accidentally trigger a "Horn" blast while they are cruising down the highway!
Key Takeaway: Use SwitchCurrentActionMap() to dynamically swap active input sets, ensuring your game only processes the inputs relevant to the player's current state.