EventTrigger动态添加监听事件

在 Unity3D 中,通过拖拽的方式在 EventTrigger 组件中添加监听事件就不多说了,很简单。这里主要说的是通过代码动态往 EventTrigger 组件中添加监听事件,有个很坑的地方,就是通过代码添加的事件,在 inspector 视图中只会显示已经为对象添加了监听事件,但具体监听事件的函数并不显示。

首先需要引用两个程序集:

using UnityEngine.Events;

using UnityEngine.EventSystems;

 

代码如下:

 using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events; public class Cube : MonoBehaviour
{
//获取自己的 EventTrigger 组件
private EventTrigger _eventTrigger;
public EventTrigger eventTrigger
{
get
{
if (_eventTrigger == null)
{
_eventTrigger = this.GetComponent<EventTrigger>();
}
return _eventTrigger;
}
} void Start()
{
AddEventTrigger(EventTriggerType.PointerEnter, Do);
} /// <summary>
/// 给自己添加监听事件
/// </summary>
/// <param name="eventType">监听事件类型</param>
/// <param name="unityAction">监听事件触发的函数</param>
private void AddEventTrigger(EventTriggerType eventType, UnityAction<BaseEventData> unityAction)
{
//判断是否有 EventTrigger 组件,没有就添加
if (eventTrigger == null)
{
this.gameObject.AddComponent<EventTrigger>();
}
//定义回掉函数,委托
UnityAction<BaseEventData> action = new UnityAction<BaseEventData>(unityAction);
//判断 EventTrigger 组件上是否已经存在监听事件,如果有就查找是否存在eventType类型的监听事件
//如果找到了,就赋值,并返回
if (eventTrigger.triggers.Count != )
{
for (int i = ; i < eventTrigger.triggers.Count; i++)
{
if (eventTrigger.triggers[i].eventID == eventType)
{
eventTrigger.triggers[i].callback.AddListener(unityAction);
return;
}
}
}
//定义所要绑定的事件类型
EventTrigger.Entry entry = new EventTrigger.Entry();
//设置事件类型
entry.eventID = eventType;
//设置回掉函数
entry.callback.AddListener(action);
//添加触发事件到EventTrigger组件上
eventTrigger.triggers.Add(entry);
}
/// <summary>
/// 触发事件需要执行的函数,由于UnityAction委托需要一个BaseEventData类型参数,所以需要设置一个BaseEventData类型的形参
/// </summary>
private void Do(BaseEventData baseEventData)
{
print();
}
}
上一篇:1055. The World's Richest (25)


下一篇:Saltstack管理对象属性之grains和pillar组件