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

如何完成Unity新输入系统迁移?2D游戏移动脚本改写求助

Unity新输入系统2D玩家控制器迁移解决方案

你的脚本存在核心问题:错误实例化输入系统类、混用新旧输入逻辑、语法错误,以及未正确绑定新输入系统的动作回调。以下是修正后的完整实现及关键改动说明:

修正后的完整脚本

using System;
using Data;
using Services.PersistenceProgress;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.InputSystem;

namespace Nick
{
    public class NickController : MonoBehaviour
    {
        [SerializeField] [Range(1, 5)] private float _speed;
        [SerializeField] private Animator _animator;
        [SerializeField] private Rigidbody2D _rigidbody2d;

        // 替换为你输入资产生成的动作类名(右键输入资产→Generate C# Class)
        private MainInputActions _inputActions;
        private Vector2 _moveInput;

        private void Awake()
        {
            _inputActions = new MainInputActions();

            // 绑定移动动作的输入回调
            _inputActions.Main.Move.performed += ctx => _moveInput = ctx.ReadValue<Vector2>();
            _inputActions.Main.Move.canceled += ctx => _moveInput = Vector2.zero;
        }

        private void OnEnable()
        {
            _inputActions.Main.Enable();
        }

        private void OnDisable()
        {
            _inputActions.Main.Disable();
        }

        void FixedUpdate()
        {
            MoveNick();
        }

        private void MoveNick()
        {
            if (GameFlow.isMovementFreezed)
            {
                _animator.SetInteger("UpDown", 0);
                _animator.SetInteger("Side", 0);
                return;
            }

            Vector2 position = _rigidbody2d.position;
            position.x += _speed * _moveInput.x * Time.fixedDeltaTime;
            position.y += _speed * _moveInput.y * Time.fixedDeltaTime;

            // 更新动画状态
            _animator.SetInteger("UpDown", _moveInput.y switch
            {
                < 0 => -1,
                > 0 => 1,
                _ => 0
            });
            _animator.SetInteger("Side", _moveInput.x switch
            {
                < 0 => -1,
                > 0 => 1,
                _ => 0
            });

            _rigidbody2d.MovePosition(position);
        }
    }
}

关键改动说明

  • 正确实例化输入动作类:原脚本错误直接创建InputSystem实例,需使用输入资产自动生成的C#类(如MainInputActions,需根据你的配置替换)。若未生成类,右键你的输入资产文件,选择Generate C# Class。
  • 绑定输入回调:通过performed和canceled事件实时获取移动输入的Vector2值,替代旧输入系统的Input.GetAxis,完全适配新输入系统的响应逻辑。
  • 移除旧输入逻辑:删除了Update中旧输入的获取代码,统一使用_moveInput变量处理移动输入。
  • 修复语法错误:修正了Awake方法的括号错误,以及未定义变量的问题。
  • 优化动画参数判断:使用switch表达式简化输入值到动画参数的映射,逻辑更清晰。

额外注意事项

  • 确保输入动作的路径与脚本一致:比如_inputActions.Main.Move中的Main是你输入配置里的动作映射名称,Move是动作名称,需和你的配置截图匹配。
  • FixedUpdate中使用Time.fixedDeltaTime保证移动逻辑的帧率稳定性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 14:44:51