【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

相关推荐
共享ui设计和前端开发人才16 小时前
UI前端大数据处理安全性保障:数据加密与隐私保护策略
ui
ui设计前端开发老司机16 小时前
UI前端大数据处理性能瓶颈突破:分布式计算框架的应用
ui
前端开发与ui设计的老司机16 小时前
UI前端与数字孪生结合实践探索:智慧物流的货物追踪与配送优化
前端·ui
UI设计和前端开发从业者20 小时前
从UI设计到数字孪生实战应用:构建智慧金融的智能风控平台
ui·金融
ui设计前端开发老司机1 天前
数字孪生技术为UI前端提供全面支持:实现产品的可视化配置与定制
ui
X_StarX1 天前
【Unity笔记01】基于单例模式的简单UI框架
笔记·ui·unity·单例模式·游戏引擎·游戏开发·大学生
Clair-Sean2 天前
【交互设计】UI 与 UX 简介:从核心概念到行业实践
ui·ux
Zevalin爱灰灰2 天前
MATLAB GUI界面设计 第六章——常用库中的其它组件
开发语言·ui·matlab
前端开发与ui设计的老司机2 天前
数字孪生技术引领UI前端设计潮流:增强现实(AR)的集成应用
ui
前端开发与ui设计的老司机2 天前
数字孪生技术为UI前端注入灵魂:实现产品全生命周期的可视化管理
前端·ui·命令模式