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

Unity新输入系统:如何通过PlayerInput组件引用动作映射?

Unity新输入系统多人游戏输入隔离解决方案

问题根源

直接通过PlayerInput类访问Gameplay动作映射是错误的——PlayerInput只是输入管理组件,本身不包含你自定义的输入动作类(你原来的controls是.inputactions资产自动生成的类实例),自然会报“找不到Gameplay定义”的错误。

无需重写核心逻辑的解决方法

方法1:通过PlayerInput获取动作映射并绑定事件

保留你的Lambda逻辑,只修改输入动作的获取方式,每个玩家用自己的PlayerInput实例隔离输入:

// 获取当前玩家的PlayerInput组件
PlayerInput playerInput = GetComponent<PlayerInput>();
// 从PlayerInput关联的动作集合中找到Gameplay映射
InputActionMap gameplayMap = playerInput.actions.FindActionMap("Gameplay");
// 找到Move动作并绑定事件
gameplayMap["Move"].performed += ctx => move = ctx.ReadValue<Vector2>();

方法2:利用PlayerInput的事件发送机制(更省心)

不用手动写绑定代码,让PlayerInput自动把输入事件传给你的脚本:

  1. 在玩家脚本中定义对应方法:
public void OnMove(InputAction.CallbackContext ctx)
{
    move = ctx.ReadValue<Vector2>();
}
  1. 选中玩家对象的PlayerInput组件,设置Behavior为Invoke Unity Events,展开Gameplay动作组,把Move的Performed事件拖拽绑定到脚本的OnMove方法上。

关键避坑点

  • 每个玩家必须有独立的PlayerInput组件,且配置不同的输入设备(比如Player1用键鼠,Player2用手柄),或通过Split Screen设置区分输入。
  • 放弃全局共享的controls实例,改用每个玩家自己的输入动作实例,彻底避免多玩家输入冲突。

内容的提问来源于stack exchange,提问作者Alpha Wolf Studios

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 13:10:31