关于unity:添加EventTrigger事件监听方法

45次阅读

共计 1136 个字符,预计需要花费 3 分钟才能阅读完成。

  /// <summary>
    /// 增加 EventTrigger 事件监听办法
    /// </summary>
    /// <param name="trans"></param>
    /// <param name="type"></param>
    /// <param name="action"></param>
    public static void AddEventTriggerHandler(this Transform trans, EventTriggerType type,UnityAction<BaseEventData> action)
    {
        EventTrigger eventTrigger = null;
        if (!trans.TryGetComponent<EventTrigger>(out eventTrigger))
        {eventTrigger = trans.gameObject.AddComponent<EventTrigger>();
        }
        if (eventTrigger.triggers == null)
        {eventTrigger.triggers = new List<EventTrigger.Entry>();
        }
        var entry = eventTrigger.triggers.FirstOrDefault(p => p.eventID == type);
        if (entry == null)
        {
            entry = new EventTrigger.Entry
            {eventID = type,};
            entry.callback.AddListener(action);
            eventTrigger.triggers.Add(entry);
        }
        else
        {entry.callback.RemoveAllListeners();
            entry.callback.AddListener(action);
        }
    }
    /// <summary>
    /// 增加带自定义参数的 EventTrigger 事件监听办法
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="trans"></param>
    /// <param name="type"></param>
    /// <param name="action"></param>
    /// <param name="t"></param>
    public static void AddEventTriggerHandler<T>(this Transform trans, EventTriggerType type, UnityAction<BaseEventData, T> action, T t)
    {
        trans.AddEventTriggerHandler(type,p =>
        {action(p,t);
        });
    }

正文完
 0