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

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类型,导致类型转换失败。

解决步骤:

  1. 打开你的输入动作配置文件(.inputactions)
  2. 找到Player/Movement动作,将其绑定修改为2D Vector Composite类型:
    • 删除当前直接绑定的W/A/S/D四个按键
    • 添加2D Vector Composite绑定,把W绑定到Up,S绑定到Down,A绑定到Left,D绑定到Right
  3. 确认该动作的Action Type设置为Value,Control Type设置为Vector2
  4. 点击配置文件工具栏的Generate C# Class,重新生成输入动作的C#类
  5. 保存配置后回到Unity,重新运行项目

额外检查项:

  • 确保CustomInput类是正确生成的,包含Player.Movement动作的正确定义
  • 确认玩家对象上已正确添加Rigidbody2D组件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 11:27:21