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

Unity移动端塔防游戏UI点击穿透BUG修复求助

移动端塔防UI点击穿透问题解决方案

针对你遇到的UI点击穿透到地块的问题,试试以下排查和修复步骤:

1. 开启UI背景面板的Raycast Target

如果你的选塔菜单有背景遮罩面板(比如半透明Image),必须勾选它的Raycast Target属性。很多情况只给按钮开了该属性,却忽略背景,导致点击按钮外的UI区域时射线仍会穿透到下方地块。

  • 选中背景面板,在Inspector的Image组件里找到Raycast Target选项并勾选。

2. 调整Canvas层级优先级

  • 确认Canvas的Sorting Layer优先级高于地块所在Layer:在Canvas的Inspector中,将Sorting Layer设置为比地块更高的层级(比如新建专属UI层并设为最高优先级)。
  • 若Canvas使用Screen Space - Camera或World Space模式,调高Order in Layer数值,确保其渲染层级高于地块。

3. 替换兼容的射线检测逻辑

你之前用的IsPointerOverGameObject()在移动端可能存在兼容性问题,改用GraphicRaycaster手动检测:

using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections.Generic;

public class GroundClickHandler : MonoBehaviour
{
    private GraphicRaycaster _uiRaycaster;
    private EventSystem _eventSystem;

    void Awake()
    {
        _uiRaycaster = FindObjectOfType<GraphicRaycaster>();
        _eventSystem = EventSystem.current;
    }

    void Update()
    {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        {
            if (IsTouchOverUI(Input.GetTouch(0).position))
                return;
            // 处理地块点击逻辑
            HandleGroundClick();
        }
    }

    bool IsTouchOverUI(Vector2 touchPos)
    {
        PointerEventData pointerData = new PointerEventData(_eventSystem);
        pointerData.position = touchPos;

        List<RaycastResult> raycastResults = new List<RaycastResult>();
        _uiRaycaster.Raycast(pointerData, raycastResults);

        return raycastResults.Count > 0;
    }

    void HandleGroundClick()
    {
        // 你的地块点击逻辑,比如弹出塔楼菜单
    }
}

4. 检查EventSystem数量

场景中只能保留一个EventSystem,多个EventSystem会导致输入检测混乱,引发穿透问题,多余的直接删除。

5. 调整输入处理顺序

把地块的点击检测放在LateUpdate中执行,确保UI事件系统先处理完输入,再响应地块点击:

void LateUpdate()
{
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
    {
        if (IsTouchOverUI(Input.GetTouch(0).position))
            return;
        HandleGroundClick();
    }
}

内容的提问来源于stack exchange,提问作者Teodor Lutoiu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:55:17