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

Unity InputSystem非performed事件读取输入值恒定输出0问题

问题原因

Unity 新输入系统默认的输入状态刷新时机为Update帧前,和物理帧FixedUpdate的调用频率不匹配,是你无法在FixedUpdate中正常读取输入值的核心原因。

可行解决方案

方案1:缓存输入值(最稳妥,适配所有场景)

输入本身是和渲染帧同步刷新的,你可以在Update中提前读取输入值缓存,在FixedUpdate中直接使用缓存值即可,同时也能保证移动效果平滑。
修改后的代码示例:

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

public class MovementEngine : MonoBehaviour
{
    public InputMaster Input; 
    public float currentSpeed = 2f;
    public float walkingSpeed = 2f;
    public float runningSpeed = 4f;
    public Transform cameraTransform;
    public CharacterController controller;
    public InputAction Movement;

    // 新增输入缓存变量
    private Vector2 _moveInputCache;

    void Awake()
    {
        Input = new InputMaster(); 
    }

    void OnEnable()
    {
        Movement = Input.Player.Movement;
        Movement.Enable(); 

        Input.Player.Interaction.performed += Interact;
        Input.Player.Interaction.Enable();
    }

    private void Interact(InputAction.CallbackContext context)
    {
        Debug.Log("Interact");
    }

    void OnDisable()
    {
        Movement.Disable();
        Input.Player.Interaction.Disable();
    }

    // 新增Update方法缓存输入
    void Update()
    {
        _moveInputCache = Movement.ReadValue<Vector2>();
    }

    void FixedUpdate(){
        Debug.Log("Movement: " + _moveInputCache); 
        // 后续移动逻辑直接使用_moveInputCache即可
    }
}

方案2:修改输入系统刷新模式

如果需要直接在FixedUpdate中读取输入值,可以修改输入系统全局配置:

  1. 打开Unity编辑器顶部菜单 Edit > Project Settings > Input System Package
  2. 将 Update Mode 选项设置为Fixed Update
    修改后输入状态会在每次FixedUpdate执行前刷新,即可直接读取到正确的输入值。

额外优化建议

你已经在OnEnable中为Movement变量赋值了输入动作的引用,后续读取输入直接使用Movement.ReadValue<Vector2>()即可,不需要重复通过Input.Player.Movement获取,避免引用变更时出现逻辑不一致的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:24:01