在Unity中,当UI与游戏对象(GameObject)相互重叠的时候,鼠标点击,则优先响应UI,并且响应最前面的UI,默认状态下,后面的UI和 GameObject 不触发事件。
如果想把鼠标点击事件一直往后传递,就在你想要穿透的UI对象上,添加脚本组件(C# Script),命名(可更改)为PassMouseEvent:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Linq;
public class PassMouseEvent : MonoBehaviour,IPointerClickHandler ,IPointerDownHandler,IPointerUpHandler
{
//监听按下
public void OnPointerDown(PointerEventData eventData)
{
PassEvent(eventData,ExecuteEvents.pointerDownHandler);
}
//监听抬起
public void OnPointerUp(PointerEventData eventData)
{
PassEvent(eventData,ExecuteEvents.pointerUpHandler);
}
//监听点击
public void OnPointerClick(PointerEventData eventData)
{
PassEvent(eventData,ExecuteEvents.submitHandler);
PassEvent(eventData,ExecuteEvents.pointerClickHandler);
}
/// <summary>
/// 把鼠标点击事件传递到下层 UI 及 GameObject
/// </summary>
private static void PassEvent<T>(PointerEventData data, ExecuteEvents.EventFunction<T> function)
where T : IEventSystemHandler
{
var results = new List<RaycastResult>();
EventSystem.current.RaycastAll(data, results);
var current = data.pointerCurrentRaycast.gameObject;
foreach (var t in results.Where(t => current != t.gameObject))
{
ExecuteEvents.Execute(t.gameObject, data, function);
//RaycastAll后ugui会自己排序,如果你只想响应透下去的最近的一个响应,这里ExecuteEvents.Execute后直接break就行。
}
}
}
把这段脚本挂在(最前面的)UI上。 然后当接收到点击事件后,调用PassEvent把当前的事件透下去。由于UGUI的事件有很多种,比如点击 、抬起、拖动、落下、第二个参数就是ExecuteEvents.Handler 把对应的Handler传进去就行了。
即可将鼠标点击事件,传递给下层 GameObject
如何为游戏对象(GameObject)添加鼠标点击事件,点我查看
参考来源:
https://www.xuanyusong.com/archives/4241