Unity Input System移动报错:无法从KeyControl读取Vector2值
问题描述
我遇到以下错误:
InvalidOperationException: 无法从绑定到动作'Player/Movement[/Keyboard/w,/Keyboard/a,/Keyboard/s,/Keyboard/d]'的控件'/Keyboard/w'读取'Vector2'类型的值(该控件是值类型为'float'的'KeyControl')
执行'Player/Movement[/Keyboard/w,/Keyboard/a,/Keyboard/s,/Keyboard/d]'的'performed'回调时出现InvalidOperationException。
我的代码如下:
using UnityEngine.InputSystem; using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { private CustomInput input = null; private Vector2 moveVector = Vector2.zero; private Rigidbody2D rb = null; private float moveSpeed = 10f; private void Awake() { input = new CustomInput(); rb = GetComponent<Rigidbody2D>(); } private void OnEnable() { input.Enable(); input.Player.Movement.performed += OnMovementPerformed; input.Player.Movement.canceled += OnMovementCancelled; } private void OnDisable() { input.Disable(); input.Player.Movement.performed -= OnMovementPerformed; input.Player.Movement.canceled -= OnMovementCancelled; } private void FixedUpdate() { rb.velocity = moveVector * moveSpeed; } private void OnMovementPerformed(InputAction.CallbackContext value){ moveVector = value.ReadValue<Vector2>(); } private void OnMovementCancelled(InputAction.CallbackContext value){ moveVector = Vector2.zero; } }
我已尝试重新生成项目文件、添加Unity.InputSystem程序集定义,请问该如何解决这个问题?
解决方案
这个错误的核心原因是Movement输入动作的绑定方式与动作类型不匹配:单个W/A/S/D按键的输出是float类型,但代码里尝试读取Vector2类型,导致类型转换失败。
解决步骤:
- 打开你的输入动作配置文件(
.inputactions) - 找到
Player/Movement动作,将其绑定修改为2D Vector Composite类型:- 删除当前直接绑定的W/A/S/D四个按键
- 添加
2D Vector Composite绑定,把W绑定到Up,S绑定到Down,A绑定到Left,D绑定到Right
- 确认该动作的
Action Type设置为Value,Control Type设置为Vector2 - 点击配置文件工具栏的
Generate C# Class,重新生成输入动作的C#类 - 保存配置后回到Unity,重新运行项目
额外检查项:
- 确保
CustomInput类是正确生成的,包含Player.Movement动作的正确定义 - 确认玩家对象上已正确添加Rigidbody2D组件
内容的提问来源于stack exchange,提问作者niceverynice123
相关产品推荐
相关产品推荐

