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

Unity多关卡2D游戏重载场景后玩家移动代码失效求助

场景重载后玩家移动失效的解决方案

针对你遇到的问题,核心原因是Player Input系统的事件绑定在场景重载后未正确触发,结合你的代码和使用的输入系统,给出以下具体解决步骤:


1. 检查Player Input组件的事件绑定方式

选中玩家对象的Player Input组件,优先使用Invoke Unity Events而非Send Messages(后者在场景重载时易出现消息丢失):

  • 将脚本中的OnMove方法改为public(OnCrouch同理)
  • 在Player Input的Actions面板中,找到Move动作,点击+号,拖拽玩家对象到事件槽,选择你的脚本名.OnMove;同样处理Crouch动作绑定

2. 代码层面确保输入事件正确订阅/取消订阅

如果习惯用代码绑定输入事件,在脚本中添加生命周期内的订阅逻辑,避免场景重载后出现订阅丢失或重复:

private PlayerInput _playerInput;
private InputAction _moveAction;
private InputAction _crouchAction;
private Vector2 movement = Vector2.zero; // 初始化movement变量

private void Awake()
{
    _playerInput = GetComponent<PlayerInput>();
    _moveAction = _playerInput.actions["Move"];
    _crouchAction = _playerInput.actions["Crouch"];

    // 订阅输入事件
    _moveAction.performed += OnMove;
    _crouchAction.performed += _ => OnCrouch();
}

private void OnDestroy()
{
    // 取消订阅,避免内存泄漏
    _moveAction.performed -= OnMove;
    _crouchAction.performed -= _ => OnCrouch();
}

public void OnMove(InputValue value)
{
    movement = value.Get<Vector2>();
}

private void OnCrouch()
{
    crouch = !crouch;
    animator.SetFloat("crouch", crouch ? 1 : 0);
}

3. 修复Player Input Manager的场景冲突

  • 将Player Input Manager对象放在主菜单场景,添加DontDestroyOnLoad逻辑,避免每次加载关卡生成重复的Manager:
private void Awake()
{
    DontDestroyOnLoad(gameObject);
}
  • 勾选Player Input Manager的Auto Assign Player Index选项,确保新加载关卡的玩家能自动获取正确的输入索引

4. 排查移动条件变量的状态

检查attacking和performing变量在场景重载后是否被正确重置为false:

  • 如果这两个变量是静态变量,改为非静态并在Awake中初始化;
  • 在Update方法开头添加Debug.Log($"attacking:{attacking}, performing:{performing}, crouch:{crouch}"),确认移动条件是否被错误触发

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 15:47:26