Unity中无法订阅onPlayerJoined与onPlayerLeft事件求助
解决Unity PlayerInputManager事件绑定错误(CS0123)
核心问题分析
CS0123错误本质是方法签名与委托要求不匹配,结合你的场景,大概率是以下原因之一:
- 未正确引用InputSystem命名空间,导致
PlayerInput类型识别错误 - PlayerInputManager的通知行为配置未对应到C#事件模式
- 方法绑定时机不合理,导致事件触发时未完成绑定
分步解决方案
1. 确保引用InputSystem命名空间
在GameManager脚本顶部添加命名空间引用,否则PlayerInput会被识别为未知类型,直接导致委托签名不匹配:
using UnityEngine.InputSystem;
2. 修正事件绑定代码
你的方法签名本身符合要求,取消注释绑定代码即可:
void OnEnable() { PlayerInputManager.instance.onPlayerJoined += OnPlayerJoined; PlayerInputManager.instance.onPlayerLeft += OnPlayerLeft; } void OnDisable() { PlayerInputManager.instance.onPlayerJoined -= OnPlayerJoined; PlayerInputManager.instance.onPlayerLeft -= OnPlayerLeft; }
注:OnPlayerLeft当前为私有方法,同一类内绑定无需修改权限;若后续需跨类调用,可改为public。
3. 配置PlayerInputManager的通知行为
确保PlayerInputManager组件的Notification Behavior设置为Invoke C# Events,其他模式(Send Messages/Invoke Unity Events)的参数传递逻辑与C#事件不同,无法直接获取PlayerInput实例。
4. 调整玩家加入的调用时机
你在Start中直接调用JoinPlayer,可能早于OnEnable的事件绑定,导致首次加入事件无法触发。建议调整初始化逻辑:
void Awake() { if (PlayerInputManager.instance == null) { Debug.LogError("未找到PlayerInputManager实例!"); return; } } void Start() { PlayerInputManager.instance.JoinPlayer(0, -1, null); PlayerInputManager.instance.JoinPlayer(1, -1, null); }
针对Send Messages/Invoke Unity Events的补充说明
如果需要使用这两种模式获取PlayerInput:
- Send Messages:方法名必须为
OnPlayerJoined,参数类型为PlayerInput,且脚本需挂载在PlayerInput的实例对象上(而非GameManager) - Invoke Unity Events:在PlayerInputManager的Unity事件面板中,绑定方法时需选择接收
PlayerInput参数的重载(若看不到重载,检查方法签名是否正确)
内容的提问来源于stack exchange,提问作者swsoft
相关产品推荐
相关产品推荐

