【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

相关推荐
神一样的老师2 天前
如何解决 Photoshop 中的“暂存盘已满”错误
ui·photoshop
伊织code2 天前
GraphRAG-Local-UI - 基于 GraphRAG 支持本地的聊天UI
ui·llm·rag·graphrag·local-ui
Avalon7123 天前
UniVue大版本更新:UniVue2.0.0-preview
游戏·ui·unity·c#
iQM754 天前
TinyVue:一款轻量级且功能强大的Vue UI组件库
前端·javascript·vue.js·ui·jenkins·excel
Logrus IT4 天前
如何提高游戏本地化的质量使用QE门户网站Logrus IT
ui·软件工程·玩游戏
Stu古月月仔5 天前
虚幻引擎-设置UI自适应屏幕大小
ui·游戏引擎·虚幻
coffee_baby5 天前
状态模式原理剖析
java·ui·ajax·设计模式·状态模式
宋小土6 天前
Naive UI 选择器 Select 的:render-label 怎么使用(Vue3 + TS)
开发语言·前端·javascript·vue.js·ui
河西石头6 天前
WPF之UI进阶--控件样式与样式模板及词典
ui·wpf·样式·模板·控件样式·样式模板·样式词典