You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity输入系统交互重绑定后默认绑定仍生效的解决方法

解决Unity输入系统重绑定后默认按键仍生效的问题

问题根源在于你的重绑定逻辑默认会新增绑定而非替换原有绑定,导致旧的默认按键绑定始终保留。以下是具体修正方案:

核心修正点

  • 指定明确的绑定索引:不要使用默认的-1作为bindingIndex,传入你要替换的默认绑定对应的索引(比如WASD绑定在动作列表中的索引,通常为0)。用-1会触发系统自动新增绑定,而非覆盖原有条目。
  • 确保绑定路径被完全覆盖:在重绑完成后,明确更新目标绑定的路径,避免旧路径残留。

修正后的代码

private void startRebinding(Button button, InputActionReference action, TMP_Text display, int bindingIndex = 0)
{
    button.interactable = false;
    display.text = waitingForInputText;
    action.action.Disable();
    playerInput.SwitchCurrentActionMap("UI");

    // 校验绑定索引有效性,防止越界或新增绑定
    if (bindingIndex < 0 || bindingIndex >= action.action.bindings.Count)
        bindingIndex = 0;

    action.action.PerformInteractiveRebinding(bindingIndex)
        .OnMatchWaitForAnother(0.1f)
        .OnComplete(operation =>
        {
            // 直接覆盖原有绑定的路径
            var targetBinding = action.action.bindings[bindingIndex];
            targetBinding.path = operation.selectedControl.path;
            action.action.UpdateBinding(bindingIndex, targetBinding);

            // 更新显示文本
            display.text = InputControlPath.ToHumanReadableString(
                targetBinding.effectivePath,
                InputControlPath.HumanReadableStringOptions.OmitDevice);

            operation.Dispose();
            button.interactable = true;

            playerInput.SwitchCurrentActionMap("Player");
            action.action.Enable();
        })
        .Start();
}

额外注意事项

  • 确认绑定索引:打开你的Input Action Asset,找到对应动作(比如Move)的绑定列表,定位默认WASD绑定的索引,调用startRebinding时传入该值。
  • 多绑定场景处理:如果动作同时支持多种输入设备(如键盘+手柄),要确保指定的索引对应你要修改的键盘绑定,避免误改其他设备的绑定。
  • 保存重绑定设置:若需要重启游戏后保留重绑定结果,可通过PlayerPrefs存储绑定路径,在游戏启动时加载并更新动作的绑定配置。

内容的提问来源于stack exchange,提问作者Peter_Gamerrr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 21:35:23