Unity安卓设备新Scene加载时阻止Button的OnClick事件误触发
方案一:重置触摸输入状态(简单直接)
在新Scene加载完成后,主动清除Unity保留的触摸输入缓存,切断Scene切换前的触摸关联。可以在Scene入口脚本的Start()或Awake()方法中添加代码:
void Start() { // 清除所有触摸状态 if (Input.touchCount > 0) { for (int i = 0; i < Input.touchCount; i++) { Input.GetTouch(i).phase = TouchPhase.Ended; } } // 重置鼠标输入兼容多场景逻辑 Input.ResetInputAxes(); }
方案二:自定义Button触发逻辑(更严谨)
重写Button的点击判断逻辑,确保只有在当前Scene内完成「按下-抬起」完整流程才触发事件:
- 创建
CustomButton.cs脚本,继承自Unity原生Button:
using UnityEngine.UI; using UnityEngine.EventSystems; public class CustomButton : Button { private bool _pressedInCurrentScene = false; public override void OnPointerDown(PointerEventData eventData) { _pressedInCurrentScene = true; base.OnPointerDown(eventData); } public override void OnPointerUp(PointerEventData eventData) { if (_pressedInCurrentScene) { base.OnPointerUp(eventData); } _pressedInCurrentScene = false; } public override void OnPointerExit(PointerEventData eventData) { _pressedInCurrentScene = false; base.OnPointerExit(eventData); } }
- 替换原有Button组件:删除原生Button,添加
CustomButton组件后重新绑定OnClick事件。
方案三:Scene加载期间禁用输入
在Scene过渡阶段禁用EventSystem,加载完成后再恢复,从根源避免跨Scene输入干扰:
- 加载Scene前执行:
// 禁用输入系统 EventSystem.current.enabled = false; SceneManager.LoadScene("目标Scene名称", LoadSceneMode.Single);
- 目标Scene加载完成后在入口脚本的
Start()中恢复:
void Start() { EventSystem.current.enabled = true; // 可选搭配方案一的输入重置 Input.ResetInputAxes(); }
内容的提问来源于stack exchange,提问作者LVBen
相关产品推荐
相关产品推荐

