Unity UGUI事件穿透

在Unity开发中,一个按钮被前面的面板挡住,但是你依然能够进行交互,这个最简单的就是把前面的面板raycast Target属性不勾选不就行了,但是如果说前面的面板也需要做事件监测的的情况下该怎样做呢,比如下图,按钮被Image挡住了,但是你依然想点击下面的Button,这个时候应该怎么办呢?在这里插入图片描述
其实Unity交互其实都是基于射线检测的,当我们检测到当前面板的时候,我们只需要将当前的事件渗透下去就行了,下面给出参考代码。

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using static UnityEngine.EventSystems.ExecuteEvents;

public class Test : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    
    
	public void OnPointerDown(PointerEventData eventData)
	{
    
    
		RaycastThrough(eventData,pointerDownHandler);
	}
	public void OnPointerUp(PointerEventData eventData)
	{
    
    
		RaycastThrough(eventData,pointerUpHandler);
	}
	public void RaycastThrough<T>(BaseEventData baseEventData, EventFunction<T> eventFunction) where T : IEventSystemHandler
	{
    
    
		PointerEventData pointerEventData = (PointerEventData)baseEventData;
		
		List<RaycastResult> raycastResults = new List<RaycastResult>();
		//当前处理的gameobject
		GameObject currentObj = pointerEventData.pointerCurrentRaycast.gameObject ?? pointerEventData.pointerDrag;
		//获取当前射线检测到的所有结果
		EventSystem.current.RaycastAll(pointerEventData, raycastResults);
		foreach (var item in raycastResults)
		{
    
    
			GameObject nextObj = item.gameObject;
			if (nextObj != null && nextObj != currentObj)
			{
    
    
				GameObject excuteObj = GetEventHandler<T>(nextObj);
				if (excuteObj != currentObj)
				{
    
    
					//执行下一层事件,如果你还需要继续执行下面层UI事件可以不return,我这里只检测下一层的,所以我循环一次就直接return
					Execute(excuteObj, pointerEventData, eventFunction);
					return;
					
				}
			}
		}
	
	}
}

有什么问题可以进群探讨

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_33547099/article/details/113478805
今日推荐