【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 天前
C# 状态模式深度解析:构建灵活的状态驱动系统
开发语言·javascript·数据库·ui·ajax·c#·ecmascript
benben0443 天前
Unity3D仿星露谷物语开发34之单击Drop项目
游戏·ui·unity·游戏引擎
benben0443 天前
Unity3D仿星露谷物语开发33之光标位置可视化
游戏·ui·unity·游戏引擎
ailinghao3 天前
使用Cusor 生成 Figma UI 设计稿
ui·ai·figma
湛谷Gooyuit4 天前
LVGL修改标签文本,GUI Guider的ui不生效
ui
baivfhpwxf20234 天前
WPF 免费UI 控件HandyControl
ui·wpf
夏之小星星4 天前
element-ui自制树形穿梭框
前端·javascript·ui·elementui·vue
Kika写代码4 天前
【Android】UI开发:XML布局与Jetpack Compose的全面对比指南
android·xml·ui
cwtlw4 天前
PhotoShop学习04
学习·ui·photoshop
baivfhpwxf20234 天前
WPF 登录页面
ui·wpf