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

Unity中父物体OnMouseDown被子Collider拦截的解决方法问询

解决Unity父物体点击事件被子物体Collider拦截的问题

方案1:禁用子物体Collider的射线检测

子物体的PolygonCollider2D用于障碍物检测,无需响应鼠标射线。找到子物体的PolygonCollider2D组件,取消勾选Raycast Target。这样该Collider不会拦截鼠标射线,父物体的BoxCollider2D可正常触发OnMouseDown,且不影响障碍物检测功能。

方案2:子物体转发点击事件给父物体

若子物体Collider必须保留射线检测能力,给子物体挂载以下脚本,将点击事件传递给父物体的Building组件:

using UnityEngine;

public class ForwardClickToParent : MonoBehaviour
{
    private Building _parentBuilding;

    void Awake()
    {
        _parentBuilding = GetComponentInParent<Building>();
    }

    void OnMouseDown()
    {
        _parentBuilding?.OnMouseDown();
    }
}

点击子物体Collider时,会自动调用父物体的选中逻辑。

方案3:手动射线检测指定父物体Layer

如果前两种方法不适用,可在父物体脚本中手动发射射线,仅检测自身Layer的Collider:

using UnityEngine;

public class Building : MonoBehaviour
{
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            var hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity, 1 << gameObject.layer);
            
            if (hit.collider?.gameObject == gameObject)
            {
                SelectBuilding();
            }
        }
    }

    void SelectBuilding()
    {
        // 此处编写你的选中逻辑
        Debug.Log("建筑已选中");
    }
}

需确保父物体与子物体不在同一Layer,或调整Layer掩码以精准检测。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:12:48