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

Unity安卓设备新Scene加载时阻止Button的OnClick事件误触发

解决Unity安卓端Button跨Scene触摸抬起误触发问题

方案一:重置触摸输入状态(简单直接)

在新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内完成「按下-抬起」完整流程才触发事件:

  1. 创建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);
    }
}
  1. 替换原有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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:33:31