Unity Android端获取当前点击UI按钮出现空引用异常如何解决?
问题排查步骤
- 先定位空引用来源:将代码拆分后增加日志打印,确认是
UnityEngine.EventSystems.EventSystem.current为空,还是currentSelectedGameObject为空。Android平台触摸输入的事件触发时机和编辑器鼠标输入存在差异,大概率是获取时机错误导致的空值。 - 检查场景EventSystem配置:确认打包生效的场景中存在且仅存在1个挂载了EventSystem组件的对象,同时该对象上仅挂载了对应输入系统的UI输入模块:用旧输入系统就挂载
Standalone Input Module,用新输入系统就挂载Input System UI Input Module,两个模块同时挂载会导致EventSystem初始化失败。 - 检查代码调用时机:不要在
Awake()、OnEnable()这类早期生命周期中直接调用该代码,此时EventSystem可能还未完成初始化;也不要在无UI交互的帧中调用,当没有任何UI对象被选中时,currentSelectedGameObject本身就会返回null。
解决方案
- 增加空值安全校验:先判断EventSystem实例是否存在,再读取选中对象,代码示例:
GameObject currentSelectedBtn = null; if (UnityEngine.EventSystems.EventSystem.current != null) { currentSelectedBtn = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject; } if (currentSelectedBtn != null) { // 执行后续业务逻辑 }
- 修正输入系统配置:打开Player Settings,确认
Active Input Handling配置和你项目用的输入系统一致:用旧输入系统选Input Manager (Old),用新输入系统选Input System Package,不要选Both兼容模式,部分Android机型下兼容模式会导致EventSystem输入模块初始化异常。 - 优先使用回调传参获取按钮:如果是在按钮的点击回调中需要获取当前点击的按钮,直接给回调方法传入按钮对象即可,不需要从EventSystem全局获取,不会出现空引用问题,示例:
// 给按钮的OnClick事件绑定该方法,同时把按钮自身拖到参数输入框 public void OnButtonClicked(GameObject clickedButton) { // 直接使用clickedButton即可 }
- 适配Android触摸获取逻辑:如果需要全局监听当前按下的UI按钮,在触摸按下的事件触发时再执行获取逻辑,代码示例:
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) { // 校验当前触摸是否点击在UI上 if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) { GameObject selectedBtn = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject; if (selectedBtn != null) { // 执行后续逻辑 } } }
内容的提问来源于stack exchange,提问作者sandy
相关产品推荐
相关产品推荐

