There is not much clear documentation on Unity's standard PlayerInput in terms of rebinding keys. This script (UnityEasyPlayerBindings) streamlines functionality of the most common and desirable control rebinding features for unity projects.
With the script, you can use simple single-line methods to:
- Rebind controls, including to specific bindings within an action or a composite action.
- Initiate an interactive rebind where the user's next input control will be bound to a desired binding.
- Get the users next input as a string binding path.
- Set a binding by binding path.
- Save and load all bindings.
To begin using EasyPlayerBindings in Unity, place the EasyPlayerBindings.cs file somewhere in your Unity project's Asset folder. Now pick/create your class which manages player input. This class should:
- Import with
using EPBindings;. - have a reference to the PlayerInput instance.
- Instantiate and store an
EasyPlayerBindingsobject.
For example:
using UnityEngine;
using EPBindings;
public class PlayerInputController : MonoBehaviour
{
[SerializeField] private PlayerInput input; //Assigned in inspector
private EasyPlayerBindings easyPlayerBindings; //To be instantiated
private void OnEnable()
{
easyPlayerBindings = new EasyPlayerBindings(input); //Create instance, passing PlayerInput object
}
}
The following action map will be used for examples.
To change any action, its parent action map must be selected.
SelectActionMap(string actionMapName)
Example: Set action map to the map called "Sample."
easyPlayerBindings.SelectActionMap("Sample")
To rebind the nth binding of a non-composite action:
RebindTo(string actionName, int bindingIndex, string newBindingPath)
Example: Binding the 'Jump' action's second binding to 'g'.
RebindTo("Dive", 1, "<Keyboard>/#(g)")
To rebind the labeled binding of a composite action:
RebindToComposite(string actionName, string compositeName, string compositeBindingName, string newBindingPath)
Example: Binding the 'Move' action's 'RightAndLeftSec' 'Negative' binding to 'g'.
RebindToComposite("Move", "RightAndLeftSec", "Negative", "<Keyboard>/#(g)")
To rebind the first/only binding of a non-composite action:
RebindTo(string actionName, string newBindingPath)
Example: Binding the 'Dive' action's only binding to 'g'.
easyPlayerBindings.RebindTo("Dive", "<Keyboard>/#(g)")
To do an interactive rebind to an action under a certain name at an index.
InteractiveRebind(string actionName, int actionBindingIndex = 0, string controlsExcluding = "")
Example: Assign the next pressed non-keyboard control to the 2nd index under the Move key.
easyPlayerBindings.InteractiveRebind("Move",2,"<keyboard>/anyKey")