- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.EventSystems;
- using UnityEngine.UI;
- public class ClickEventPenetration : MonoBehaviour, IPointerClickHandler
- {
- private List
raycastResults; -
- private void Awake()
- {
- raycastResults = new List
(); - }
-
- public void OnPointerClick(PointerEventData eventData)
- {
- //获取当前事件所有触发对象
- EventSystem.current.RaycastAll(eventData, raycastResults);
- foreach (var v in raycastResults)
- {
- //过滤自身点击事件(不过滤会死循环,下面也会执行到这个对象脚本的OnPointerClick方法)
- if (v.gameObject.GetComponent
()) - {
- 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