在 Unity3D 中,通过拖拽的方式在 EventTrigger 组件中添加监听事件就不多说了,很简单。这里主要说的是通过代码动态往 EventTrigger 组件中添加监听事件,有个很坑的地方,就是通过代码添加的事件,在 inspector 视图中只会显示已经为对象添加了监听事件,但具体监听事件的函数并不显示。
首先需要引用两个程序集:
using UnityEngine.Events;
using UnityEngine.EventSystems;
代码如下:
1 using UnityEngine; 2 using UnityEngine.EventSystems; 3 using UnityEngine.Events; 4 5 public class Cube : MonoBehaviour 6 { 7 //获取自己的 EventTrigger 组件 8 private EventTrigger _eventTrigger; 9 public EventTrigger eventTrigger 10 { 11 get 12 { 13 if (_eventTrigger == null) 14 { 15 _eventTrigger = this.GetComponent<EventTrigger>(); 16 } 17 return _eventTrigger; 18 } 19 } 20 21 void Start() 22 { 23 AddEventTrigger(EventTriggerType.PointerEnter, Do); 24 } 25 26 /// <summary> 27 /// 给自己添加监听事件 28 /// </summary> 29 /// <param name="eventType">监听事件类型</param> 30 /// <param name="unityAction">监听事件触发的函数</param> 31 private void AddEventTrigger(EventTriggerType eventType, UnityAction<BaseEventData> unityAction) 32 { 33 //判断是否有 EventTrigger 组件,没有就添加 34 if (eventTrigger == null) 35 { 36 this.gameObject.AddComponent<EventTrigger>(); 37 } 38 //定义回掉函数,委托 39 UnityAction<BaseEventData> action = new UnityAction<BaseEventData>(unityAction); 40 //判断 EventTrigger 组件上是否已经存在监听事件,如果有就查找是否存在eventType类型的监听事件 41 //如果找到了,就赋值,并返回 42 if (eventTrigger.triggers.Count != 0) 43 { 44 for (int i = 0; i < eventTrigger.triggers.Count; i++) 45 { 46 if (eventTrigger.triggers[i].eventID == eventType) 47 { 48 eventTrigger.triggers[i].callback.AddListener(unityAction); 49 return; 50 } 51 } 52 } 53 //定义所要绑定的事件类型 54 EventTrigger.Entry entry = new EventTrigger.Entry(); 55 //设置事件类型 56 entry.eventID = eventType; 57 //设置回掉函数 58 entry.callback.AddListener(action); 59 //添加触发事件到EventTrigger组件上 60 eventTrigger.triggers.Add(entry); 61 } 62 /// <summary> 63 /// 触发事件需要执行的函数,由于UnityAction委托需要一个BaseEventData类型参数,所以需要设置一个BaseEventData类型的形参 64 /// </summary> 65 private void Do(BaseEventData baseEventData) 66 { 67 print(123); 68 } 69 }