【Unity3D】实现UI点击事件穿透

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ClickEventPenetration : MonoBehaviour, IPointerClickHandler
{
    private List<RaycastResult> raycastResults;

    private void Awake()
    {
        raycastResults = new List<RaycastResult>();
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        //获取当前事件所有触发对象
        EventSystem.current.RaycastAll(eventData, raycastResults);
        foreach (var v in raycastResults)
        {
            //过滤自身点击事件(不过滤会死循环,下面也会执行到这个对象脚本的OnPointerClick方法)
            if (v.gameObject.GetComponent<ClickEventPenetration>())
            {
                Debug.LogWarning(v.gameObject);
                continue;
            }
            Debug.Log(v.gameObject);

            //执行触发对象的点击事件
            //ExecuteEvents.Execute(v.gameObject, eventData, ExecuteEvents.pointerClickHandler);

            //仅仅执行物体标签为INeedClick的UI点击事件
            if (v.gameObject.tag == "INeedClick")
            {
                //IPointerClickHandler接口需要传递ExecuteEvents.pointerClickHandler类型进入,其他接口同理
                ExecuteEvents.Execute(v.gameObject, eventData, ExecuteEvents.pointerClickHandler);
            }
        }
    }

    //测试案例直接用这个公共方法作为INeedClickButton的Click事件(直接拽拖赋值)
    public void OnINeedClick()
    {
        Debug.LogError("OnINeedClick!");
    }
}

注意:EventSystem.current.RaycastAll获取到的对象列表是能够接受事件的,假如你的按钮Button自己身上没有Image,而是Button的子物体有,那么你就要给这个子物体也加上标签Tag才能响应到。

如果ExecuteEvents.Execute不管用,可以试试ExecuteEvents.ExecuteHierarchy

相关推荐
步、步、为营8 小时前
.NET8 正式发布, C#12 新变化
ui·c#·.net
伽蓝_游戏9 小时前
Unity UI的未来之路:从UGUI到UI Toolkit的架构演进与特性剖析(7)
游戏·ui·unity·架构·c#·游戏引擎·.net
安卓开发者2 天前
Jetpack Compose for XR:构建下一代空间UI的完整指南
ui·xr
伽蓝_游戏2 天前
Unity UI的未来之路:从UGUI到UI Toolkit的架构演进与特性剖析(6)
游戏·ui·unity·架构·c#·游戏引擎·.net
笑尘pyrotechnic2 天前
自动布局视图来实现聊天室的界面
ui·ios·objective-c
小梦白2 天前
RPG增容3:尝试使用MVC结构搭建玩家升级UI(一)
游戏·ui·ue5·mvc
小妖6663 天前
Next.js 怎么使用 Chakra UI
前端·javascript·ui
唐 城3 天前
【可用有效】Axure RP 9 授权码
ui·photoshop
wuk9984 天前
Android:UI:Drawable:View/ImageView与Drawable
android·ui