手动添加EventTrigger的事件固然方便,但是不利于以后的修改,所以用代码添加是很有必要的。
起初使用的时候是参考了各家博主的代码,都大致相似,就直接拿来。但是当我要在一个EventTrigger下添加多个事件的时候,代码就冗余了,干脆封成一个方法,用起来方便,主要是不用费心思给那些临时变量起名字了。
代码如下:
/// <summary>
/// 添加EventTrigger的监听事件
/// </summary>
/// <param name="obj">添加监听的对象</param>
/// <param name="eventID">添加的监听类型</param>
/// <param name="action">触发方法</param>
private void AddTriggersListener(GameObject obj, EventTriggerType eventID, UnityAction<BaseEventData> action)
{
EventTrigger trigger = obj.GetComponent<EventTrigger>();
if (trigger == null)
{
trigger = obj.AddComponent<EventTrigger>();
}
if (trigger.triggers.Count == 0)
{
trigger.triggers = new List<EventTrigger.Entry>();
}
UnityAction<BaseEventData> callback = new UnityAction<BaseEventData>(action);
EventTrigger.Entry entry = new EventTrigger.Entry();
entry.eventID = eventID;
entry.callback.AddListener(callback);
trigger.triggers.Add(entry);
}
使用示例:
//播放进度条EventTrigger监听
AddTriggersListener(sliderProgressBar.gameObject, EventTriggerType.PointerEnter, OnVideoPointerEnter);
AddTriggersListener(sliderProgressBar.gameObject, EventTriggerType.PointerExit, OnVideoPointerExit);
AddTriggersListener(sliderProgressBar.gameObject, EventTriggerType.PointerClick, OnVideoPointerClick);
AddTriggersListener(sliderProgressBar.gameObject, EventTriggerType.BeginDrag, OnVideoBeginDrag);
AddTriggersListener(sliderProgressBar.gameObject, EventTriggerType.EndDrag, OnVideoEndDrag);