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

Unity新输入系统:如何获取输入动作的实时数值?

Unity新Input System无法获取Movement实时X轴值的解决方法

核心问题分析

你的代码存在3个关键错误,导致无法读取Movement的实时数值:

  1. ReadValue的类型与语法错误
  2. PlayerInput组件的赋值顺序错误
  3. 输入值读取逻辑的实现问题

分步修正方案

1. 修正ReadValue的调用方式

你写的playerInput.Movement.ReadValue<Vector>有两处错误:

  • 2D输入的正确类型是Vector2,而非Vector
  • ReadValue是方法,必须加括号调用

正确写法:

playerInput.Movement.ReadValue<Vector2>()

2. 调整Start方法的赋值顺序

你先打印了playerInput.currentActionMap,之后才给playerInput赋值,会导致空引用错误。修改后:

void Start()
{
    rigiBody = ownPlayer.GetComponent<Rigidbody2D>();
    playerInput = GetComponent<PlayerInput>(); // 先获取组件
    Debug.Log(playerInput.currentActionMap); // 再打印动作映射
}

3. 正确读取Movement的X轴值

有两种可靠方式获取输入值:

方式一:在FixedUpdate中主动读取

适合需要实时帧更新的移动逻辑:

void FixedUpdate()
{
    Vector2 movement = playerInput.Movement.ReadValue<Vector2>();
    Debug.Log("Movement X轴实时值:" + movement.x);
    // 示例:用X轴值控制玩家移动
    // rigiBody.velocity = new Vector2(movement.x * 5f, rigiBody.velocity.y);
}

方式二:通过回调接收输入值

如果你的PlayerInput使用Send Messages或Invoke Unity Events模式,推荐用带参数的回调方法:

void OnMovement(InputValue value)
{
    moveDirection = value.Get<Vector2>();
    Debug.Log("Movement X轴值:" + moveDirection.x);
}

完整修正代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class S_PlayerInputs : MonoBehaviour
{
    public PlayerInput playerInput;
    public GameObject ownPlayer;
    Rigidbody2D rigiBody;
    Vector2 moveDirection = Vector2.zero;

    void Start()
    {
        rigiBody = ownPlayer.GetComponent<Rigidbody2D>();
        playerInput = GetComponent<PlayerInput>();
        Debug.Log(playerInput.currentActionMap);
    }

    void FixedUpdate()
    {
        Vector2 movement = playerInput.Movement.ReadValue<Vector2>();
        Debug.Log("Movement X轴实时值:" + movement.x);
    }

    void OnJump()
    {
        rigiBody.velocity = new Vector2(rigiBody.velocity.x, 10);
        Debug.Log("Player jumped!");
    }

    void OnMovement(InputValue value)
    {
        moveDirection = value.Get<Vector2>();
        Debug.Log("Movement回调X轴值:" + moveDirection.x);
    }
}

额外检查项

  • 确认Input Action Map中,Movement动作的Type设为Value,Control Type设为Vector2
  • 检查PlayerInput组件的Action Map选择了正确的映射
  • 确保Movement动作已绑定A/D或方向键等输入控件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 00:47:23