美文网首页
Unity3d UGUI 添加事件

Unity3d UGUI 添加事件

作者: CappuccinoBx | 来源:发表于2017-07-06 15:17 被阅读0次

    话不多说直接上代码,两个方法的功能分别是添加事件和删除事件。

        /// <summary>
        /// 添加UGUI的EventTrigger事件
        /// </summary>
        /// <param name="target">添加对象</param>
        /// <param name="type">事件类型</param>
        /// <param name="callback">调用函数</param>
        public static void AddUGUIEvent(GameObject target, EventTriggerType type, UnityAction<BaseEventData> callback)
        {
            EventTrigger trigger = target.GetComponent<EventTrigger>();
            if (trigger == null)
                trigger = target.AddComponent<EventTrigger>();
    
            //是否新增事件类型
            bool IsNew = false;
            if (trigger.triggers.Count == 0)
            {
                trigger.triggers = new List<EventTrigger.Entry>();
                IsNew = true;
            }
            else
            {
                for (int i = 0; i < trigger.triggers.Count; i++)
                {
                    if (trigger.triggers[i].eventID == type)
                    {
                        //如果已经有该类型的事件类型,则新增事件至事件调用列表
                        trigger.triggers[i].callback.AddListener(callback);
                    }
                    else
                    {
                        IsNew = true;
                    }
                }
            }
    
            //添加一个新的事件类型的监听
            if (IsNew)
            {
                EventTrigger.Entry entry = new EventTrigger.Entry();
                entry.eventID = type;
                entry.callback = new EventTrigger.TriggerEvent();
    
                entry.callback.AddListener(callback);
                trigger.triggers.Add(entry);
            }
        }
    
        /// <summary>
        /// 删除组件的UGUI EventTrigger事件
        /// </summary>
        /// <param name="target">添加对象</param>
        /// <param name="type">事件类型</param>
        /// <param name="callback">调用函数</param>
        public static void RemoveUGUIEvent(GameObject target, EventTriggerType type, UnityAction<BaseEventData> callback)
        {
            EventTrigger trigger = target.GetComponent<EventTrigger>();
            if (trigger == null)
            {
                Debug.LogError(string.Format("No EventTrigger on '{0}' !", target.name));
                return;
            }
            if (trigger.triggers == null || trigger.triggers.Count == 0)
            {
                Debug.LogError(string.Format("Object '{0}' triggers list is not correct !"));
            }
            List<EventTrigger.Entry> list = trigger.triggers;
            for (int i = list.Count - 1; i >= 0; i--)
            {
                if (list[i].eventID == type)
                {
                    list[i].callback.RemoveListener(callback);
                }
            }
        }
    

    相关文章

      网友评论

          本文标题:Unity3d UGUI 添加事件

          本文链接:https://www.haomeiwen.com/subject/uybhhxtx.html