Unity Input System中Vector2按键重绑如何取消Esc限制及使用WithControlsHavingToMatchPath?
Unity Input System:解除Vector2动作绑定单键限制 + WithControlsHavingToMatchPath用法指引
一、解除Vector2动作绑定Esc等单键的限制
Input System在InputActionRebindingExtensions.cs第2760行的拦截逻辑,本质是默认校验控件类型与动作预期类型匹配:Vector2动作默认要求绑定轴类控件(比如方向键、摇杆),而Esc属于按钮控件,因此被阻止。
无需修改内部脚本,通过RebindingOperation的自定义验证逻辑即可绕开限制:
// 假设你有一个名为movementAction的Vector2类型InputAction var rebindOp = movementAction.PerformInteractiveRebinding() // 自定义匹配逻辑:允许所有控件(包括按钮) .WithMatchingControlsPredicate(control => true) // 可选:若仅需放开Esc这类特定按钮,可针对性判断 // .WithMatchingControlsPredicate(control => control.path == "<Keyboard>/escape" || control.valueType == typeof(Vector2)) .OnComplete(op => { Debug.Log("绑定完成:" + op.selectedControl.path); op.Dispose(); }) .Start();
WithMatchingControlsPredicate会替换默认类型检查,返回true即允许该控件被选中,按需调整判断条件即可实现精准放开限制。
二、WithControlsHavingToMatchPath函数用法(官方文档翻译+示例)
函数说明(翻译自官方1.0版本文档)
WithControlsHavingToMatchPath(string path) 是RebindingOperation的扩展方法,用于限制交互式重绑过程中,仅能选择符合指定路径模板的控件。路径模板支持通配符(如"<Gamepad>/*"匹配所有手柄控件)。
核心作用
- 精确缩小可绑定控件范围,比如仅允许绑定键盘方向键、仅允许绑定手柄左摇杆
- 路径模板遵循Input System的控件路径语法,支持通配符
*(匹配任意子路径)和?(匹配单个字符)
用法示例
示例1:仅允许绑定键盘字母键
// 假设你有一个名为jumpAction的InputAction var rebindOp = jumpAction.PerformInteractiveRebinding() .WithControlsHavingToMatchPath("<Keyboard>/a*") // 匹配所有以a开头的键盘按键 .OnComplete(op => { Debug.Log("绑定了字母键:" + op.selectedControl.path); op.Dispose(); }) .Start();
示例2:仅允许绑定手柄摇杆轴
var rebindOp = movementAction.PerformInteractiveRebinding() .WithControlsHavingToMatchPath("<Gamepad>/leftStick/*") // 匹配左摇杆的X/Y轴 .OnComplete(op => { Debug.Log("绑定了左摇杆轴:" + op.selectedControl.path); op.Dispose(); }) .Start();
示例3:组合多筛选条件
若需同时限制路径和控件类型,可与WithMatchingControlsPredicate组合使用:
var rebindOp = movementAction.PerformInteractiveRebinding() .WithControlsHavingToMatchPath("<Keyboard>/*") // 仅允许键盘控件 .WithMatchingControlsPredicate(control => control.valueType == typeof(float) || control.valueType == typeof(Vector2)) // 允许轴或Vector2类型控件 .OnComplete(op => { Debug.Log("绑定完成"); op.Dispose(); }) .Start();
内容的提问来源于stack exchange,提问作者Noob_GameDev
相关产品推荐
相关产品推荐

