这个可以自定义UI元素的点击,拖拽等事件。
核心方法:在代码里面定义一个委托,脚本继承EventTrigger搞就完了,直接代码:
using UnityEngine; using UnityEngine.EventSystems; public class EventTriggerListener : EventTrigger { public delegate void MouseAction(GameObject go); public MouseAction onEnter; public MouseAction onExit; public MouseAction onClick; public static EventTriggerListener Get(GameObject go) { EventTriggerListener eventTriggerListener = go.GetComponent<EventTriggerListener>(); if (eventTriggerListener == null) { eventTriggerListener = go.AddComponent<EventTriggerListener>(); } return eventTriggerListener; } public override void OnPointerClick(PointerEventData eventData) { base.OnPointerClick(eventData); onClick?.Invoke(gameObject); } public override void OnPointerEnter(PointerEventData eventData) { base.OnPointerEnter(eventData); onEnter?.Invoke(gameObject); } public override void OnPointerExit(PointerEventData eventData) { base.OnPointerExit(eventData); onExit?.Invoke(gameObject); } }
PS:上面代码在CS 4以下运行会报错,委托执行方式改为:
if(onClick!=null){
onClick(gameObject);
}
调用的时候获取到物体的GameObject,直接用:
EventTriggerListener.Get(gameObject).onClick += (go)=>{ Debug.Log(go.name); };
可以自由扩展,需要什么事件就在下面重写事件就好啦。
就这样。拜拜~