【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

相关推荐
黑金IT14 小时前
Python3 + Qt5:实现AJAX异步更新UI
qt·ui·ajax
喵叔哟20 小时前
5. 【Vue实战--孢子记账--Web 版开发】-- 主页UI
前端·vue.js·ui
山海青风1 天前
Axure入门教程 -- 第五章:原型优化与调试
ui·交互·axure
浅陌sss3 天前
Unity 粒子特效在UI中使用裁剪效果
ui·unity·游戏引擎
机器视觉小小测试员3 天前
工业相机常用词语解释
运维·ui·自动化·工业相机
PersistJiao4 天前
Couchbase UI: Search
ui·couchbase
时光追逐者4 天前
一组开源、免费、Metro风格的 WPF UI 控件库
ui·开源·c#·.net·wpf·.netcore·微软技术
专注VB编程开发20年5 天前
代替Winform、Win32控件的一些界面框架Electron,QT等
前端·c++·ui·框架·界面
军训猫猫头5 天前
58.界面参数传递给Command C#例子 WPF例子
开发语言·ui·c#·wpf
半城风月-6 天前
Vue 2 + Element UI 实现密码显示、隐藏切换功能
vue.js·ui·elementui