In this lesson, you will learn how to empower your players to customize their gameplay experience by implementing a runtime rebinding system for your Input Actions.
When players want to change their controls, we don't need to manually map every key in our code. Instead, we use the InputActionRebindingExtensions class provided by the New Input System. This allows us to take an existing InputAction and "listen" for a new key press from the player to replace the current binding.
The Rebinding Workflow
To implement this, you need to create a UI button that, when clicked, triggers a rebinding operation. The process involves three main steps:
- Disable the Action: You must disable the
InputActionbefore modifying its bindings. - Start the Operation: Use
PerformInteractiveRebinding()on the specific action. - Clean Up: Once the user presses a key, call
Dispose()on the operation to free up memory and re-enable the action.
Here is how you can implement a simple rebinding trigger:
using UnityEngine;
using UnityEngine.InputSystem;
public class RebindUI : MonoBehaviour
{
public InputActionReference actionToRebind;
public void StartRebinding()
{
// 1. Disable the action
actionToRebind.action.Disable();
// 2. Start the interactive process
var rebindOp = actionToRebind.action.PerformInteractiveRebinding()
.OnComplete(operation =>
{
// 3. Clean up and re-enable
operation.Dispose();
actionToRebind.action.Enable();
Debug.Log("Binding updated!");
})
.Start();
}
}
By using PerformInteractiveRebinding(), Unity automatically handles the "Listening for Input" state for you. The user simply triggers the UI, presses their desired key, and the system swaps the binding internally. This approach ensures that your game remains modular and that your input logic remains decoupled from the specific keys being pressed.
Always ensure you store these changes if you want them to persist between game sessions; the Input System provides methods to save and load these binding overrides as JSON strings, which you can then save to a local file or PlayerPrefs.
Key Takeaway: By using PerformInteractiveRebinding(), you can offload the complex task of detecting new key presses to Unity, allowing you to easily build flexible, user-friendly control menus.