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!");
}
}
Note: The object list obtained by EventSystem.current.RaycastAll can accept events. If your button Button itself does not have an Image, but a sub-object of the Button does, then you have to add a tag to the sub-object. respond to.
If ExecuteEvents.Execute doesn't work, you can try ExecuteEvents.ExecuteHierarchy