TExcelTAD
Home › Unity with C# › Rebinding, Gamepad & Touch

Rebinding, Gamepad & Touch

Players expect to remap keys, use a gamepad without configuration, and play mobile games with touch. The Input System handles all three on top of the actions from the previous lesson.

Interactive rebinding

A rebinding operation listens for the next control the player actuates and stores it as a binding override. The original binding in the asset is untouched, so "reset to defaults" is just removing overrides.

csharp
using UnityEngine;
using UnityEngine.InputSystem;

public class RebindButton : MonoBehaviour
{
    [SerializeField] InputActionReference actionRef;
    [SerializeField] int bindingIndex;                 // which binding of the action to replace
    [SerializeField] TMPro.TMP_Text label;
    InputActionRebindingExtensions.RebindingOperation operation;

    public void StartRebind()                          // hooked to a UI button
    {
        InputAction action = actionRef.action;
        action.Disable();                              // an action must be disabled while rebinding
        label.text = "Press a key...";

        operation = action.PerformInteractiveRebinding(bindingIndex)
            .WithControlsExcluding("<Mouse>/position")    // ignore mouse movement
            .WithCancelingThrough("<Keyboard>/escape")
            .OnMatchWaitForAnother(0.1f)                  // avoid grabbing a key that was already held
            .OnComplete(_ => Finish(action))
            .OnCancel(_ => Finish(action))
            .Start();
    }

    void Finish(InputAction action)
    {
        operation.Dispose();                           // operations hold native memory
        action.Enable();
        label.text = action.GetBindingDisplayString(bindingIndex);
        PlayerPrefs.SetString("rebinds", action.actionMap.asset.SaveBindingOverridesAsJson());
    }
}

Load the saved overrides at startup with asset.LoadBindingOverridesFromJson(PlayerPrefs.GetString("rebinds")) and reset with action.RemoveAllBindingOverrides(). The Input System package also ships a Rebinding UI sample (import it from the package's Samples tab in the Package Manager) with a complete, reusable rebind widget.

A model of binding overrides

The model stores default bindings and overrides separately, detects conflicts (two actions on one key), saves overrides as JSON, and loads them into a fresh session:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;

var defaults = new Dictionary<string, string>
{
    ["Jump"] = "<Keyboard>/space", ["Interact"] = "<Keyboard>/e", ["Sprint"] = "<Keyboard>/leftShift",
};
var session = new Bindings(defaults);

session.Rebind("Jump", "<Keyboard>/w");
session.Rebind("Sprint", "<Keyboard>/e");          // conflicts with Interact
string json = session.SaveOverrides();
Console.WriteLine(
quot;saved: {json}"); var nextLaunch = new Bindings(defaults); nextLaunch.LoadOverrides(json); foreach (var action in defaults.Keys) Console.WriteLine(
quot;{action,-8} -> {nextLaunch.Effective(action)}"); nextLaunch.ResetAll(); Console.WriteLine(
quot;after reset: Jump -> {nextLaunch.Effective("Jump")}"); class Bindings { readonly Dictionary<string, string> defaults; Dictionary<string, string> overrides = new(); public Bindings(Dictionary<string, string> d) => defaults = d; public string Effective(string action) => overrides.TryGetValue(action, out var o) ? o : defaults[action]; public void Rebind(string action, string path) { var clash = defaults.Keys.FirstOrDefault(a => a != action && Effective(a) == path); if (clash != null) { overrides[clash] = Effective(action); // swap, like many games do Console.WriteLine(
quot;{path} was used by {clash}; {clash} now uses {overrides[clash]}"); } overrides[action] = path; } public string SaveOverrides() => JsonSerializer.Serialize(overrides.OrderBy(kv => kv.Key).ToDictionary()); public void LoadOverrides(string json) => overrides = JsonSerializer.Deserialize<Dictionary<string, string>>(json)!; public void ResetAll() => overrides.Clear(); }
<Keyboard>/e was used by Interact; Interact now uses <Keyboard>/leftShift
saved: {"Interact":"\u003CKeyboard\u003E/leftShift","Jump":"\u003CKeyboard\u003E/w","Sprint":"\u003CKeyboard\u003E/e"}
Jump     -> <Keyboard>/w
Interact -> <Keyboard>/leftShift
Sprint   -> <Keyboard>/e
after reset: Jump -> <Keyboard>/space

System.Text.Json escapes < and > by default (as \u003C and \u003E), which is harmless: the values load back unchanged. Only the overrides are saved, so a game update that changes a default binding still reaches players who never touched that action, and ResetAll brings back the defaults by clearing the overrides.

Gamepads

Bindings like <Gamepad>/buttonSouth work for Xbox (A), PlayStation (Cross) and Switch Pro controllers alike, because the Input System names buttons by position. Show the right glyph by asking for the display string of the control that's actually in use. Direct device access is available too, for debugging or effects:

csharp
using UnityEngine.InputSystem;

var pad = Gamepad.current;                         // null when no gamepad is connected
if (pad != null)
{
    if (pad.buttonSouth.wasPressedThisFrame) Jump();
    pad.SetMotorSpeeds(0.2f, 0.6f);                // rumble: low- and high-frequency motors
}
// ... later: pad.ResetHaptics();

Listen to InputSystem.onDeviceChange to pause the game when a controller disconnects; console certification requires it.

Touch

For simple games, bind actions to <Touchscreen>/primaryTouch/position and <Touchscreen>/primaryTouch/press, or use the On-Screen Stick and On-Screen Button components on UI elements, which feed virtual gamepad controls into your existing actions. For multi-touch gestures use the Enhanced Touch API:

csharp
using UnityEngine;
using UnityEngine.InputSystem.EnhancedTouch;
using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch;

public class PinchZoom : MonoBehaviour
{
    void OnEnable()  => EnhancedTouchSupport.Enable();
    void OnDisable() => EnhancedTouchSupport.Disable();

    void Update()
    {
        if (Touch.activeTouches.Count != 2) return;
        Touch a = Touch.activeTouches[0], b = Touch.activeTouches[1];
        float now = Vector2.Distance(a.screenPosition, b.screenPosition);
        float before = Vector2.Distance(a.screenPosition - a.delta, b.screenPosition - b.delta);
        Camera.main.fieldOfView = Mathf.Clamp(Camera.main.fieldOfView - (now - before) * 0.05f, 30f, 80f);
    }
}

In the editor, test touch without a phone with the Device Simulator: switch the Game view to Simulator with the drop-down at the left of its toolbar, and pick a phone model.

Test yourself

What must you do with an action before starting PerformInteractiveRebinding?

  1. Delete its bindings
  2. Disable it
  3. Save the project
  4. Switch to the old Input Manager

Why does <Gamepad>/buttonSouth work on Xbox and PlayStation controllers?

  1. Both use the same hardware
  2. Gamepad buttons are named by position, not by label
  3. It only works on Xbox
  4. The binding is translated at build time

How are rebinding results usually persisted?

  1. By editing the .inputactions asset at runtime
  2. SaveBindingOverridesAsJson() stored in PlayerPrefs or a settings file
  3. In the scene file
  4. They can't be saved