Unity3d UGUI 添加事件

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

    /// 
    /// 添加UGUI的EventTrigger事件
    /// 
    /// 添加对象
    /// 事件类型
    /// 调用函数
    public static void AddUGUIEvent(GameObject target, EventTriggerType type, UnityAction callback)
    {
        EventTrigger trigger = target.GetComponent();
        if (trigger == null)
            trigger = target.AddComponent();

        //是否新增事件类型
        bool IsNew = false;
        if (trigger.triggers.Count == 0)
        {
            trigger.triggers = new List();
            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);
        }
    }

    /// 
    /// 删除组件的UGUI EventTrigger事件
    /// 
    /// 添加对象
    /// 事件类型
    /// 调用函数
    public static void RemoveUGUIEvent(GameObject target, EventTriggerType type, UnityAction callback)
    {
        EventTrigger trigger = target.GetComponent();
        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 list = trigger.triggers;
        for (int i = list.Count - 1; i >= 0; i--)
        {
            if (list[i].eventID == type)
            {
                list[i].callback.RemoveListener(callback);
            }
        }
    }

你可能感兴趣的:(Unity3d UGUI 添加事件)