【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

相关推荐
UXbot11 小时前
为什么 AI 正在重新定义 UI 设计工具的入门门槛
前端·人工智能·低代码·ui·交互·ai编程·ux
IT go11 小时前
用 Trae + Stitch MCP 打造 UI 自动化产出工作流(从设计到本地预览)
ui·自动化
熙胤19 小时前
Spring Boot 3.x 引入springdoc-openapi (内置Swagger UI、webmvc-api)
spring boot·后端·ui
lpfasd12320 小时前
Kubernetes UI 管理全景指南
ui·容器·kubernetes
武藤一雄21 小时前
WPF UI 开发深度指南:资源 (Resources)、样式 (Style) 与触发器 (Trigger) 全解析
ui·c#·.net·wpf·.netcore·avalonia
Swift社区1 天前
ArkUI 的 UI 复用机制解析
人工智能·ui·arkui
九转成圣1 天前
解决 Element UI Upload 组件二次上传不发请求的极简方案
ui
JamesYoung79711 天前
第八部分 — UI 表面 options 页面模式
ui
JosieBook2 天前
【WinForm】C# WinForms 跨线程更新 UI 避坑指南
开发语言·ui·c#
喵叔哟2 天前
17. 【Blazor全栈开发实战指南】--Blazor UI框架集成
ui·微服务·.net