【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

相关推荐
类人_猿10 小时前
PhotoShop批处理
ui·photoshop·批处理·photoshop批处理
PM大明同学11 小时前
Axure PR 9 中继器 02 分页提示
ui·交互·产品经理·axure
十秒耿直拆包选手11 小时前
cmake:定位Qt的ui文件
c++·qt·ui·cmake
engchina12 小时前
使用 Vite + React 19 集成 Tailwind CSS 与 shadcn/ui 组件库完整指南
css·react.js·ui·vite·tailwind·react 19·shadcn
1024小神16 小时前
ios苹果手机使用AScript应用程序实现UI自动化操作,非常简单的一种方式
运维·ui·自动化
画月的亮1 天前
element-ui 使用过程中遇到的一些问题及解决方法
javascript·vue.js·ui
Jackson@ML2 天前
React入门 – 1. 学习React的预备知识
javascript·react.js·ui
laimaxgg2 天前
Qt常用控件之按钮QPushButton
开发语言·c++·qt·ui·qt5
小王不会写code2 天前
Element UI常用组件
javascript·vue.js·ui
招风的黑耳2 天前
数据大屏炫酷UI组件库:B端科技风格PSD资源集
科技·ui