UGUI 代码 动态添加 Event Trigger 的事件

Additionally, if you need more than just the events provided by default, I'd suggest instead attaching a EventTrigger to your game object. This gives us access to the BaseEventData object returned from the event, telling us stuff like the object that created the event. Then you can do something like:

//Create an event delegate that will be used for creating methods that respond to events 
public delegate void EventDelegate(UnityEngine.EventSystems.BaseEventData baseEvent);

Then we can create a method for handling events, the signature must match that of our delegate. So, it needs to return void and accept BaseEventData as its first and only parameter:

public void DropEventMethod(UnityEngine.EventSystems.BaseEventData baseEvent)
 { Debug.Log(baseEvent.selectedObject.name + " triggered an event!"); 
//baseEvent.selectedObject is the GameObject that triggered the event,
 // so we can access its components, destroy it, or do whatever. 
}

动态添加 EventTrigger 代码如下,

//从UI gameobject上面获取到 eventtrigger 
EventTrigger eventTrigger = buttonObject.GetComponent<EventTrigger>();  
//创建一个新的 trigger。 在这个trigger上添加事件类型和回调函数 
EventTrigger.Entry entry = new EventTrigger.Entry();  
//设置这个eventtrigger的事件类型为 Drop 
entry.eventID = EventTriggerType.Drop;  
//初始化callback entry.callback = new EventTrigger.TriggerEvent();  
//创建一个新的UnityAction, 里面就是我们写的回调函数 
UnityEngine.Events.UnityAction<BaseEventData> callback = new UnityEngine.Events.UnityAction<BaseEventData>(DropEventMethod);  
//添加到trigger 的 callback里面 
entry.callback.AddListener(callback); 
 //最后添加到物体的eventtriger的trigger里面 
eventTrigger.trigger.Add(entry);
posted @ 2015-09-30 16:58  月月鸟在前进  阅读(2281)  评论(0编辑  收藏  举报