事件管理器
项目开发过程中经常会用到代理事件,为方便管理,避免代码混乱,需要一个总的事件管理器:
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; public class EventManager<T> { private static Dictionary<EventType,List<Action<T>>> eventDic = new Dictionary<EventType,List<Action<T>>>(); /// <summary> /// 添加事件 /// </summary> /// <param name="type"></param> /// <param name="act"></param> public static void AddEvent(EventType type, Action<T> act) { if (eventDic.ContainsKey(type)) { if(!eventDic[type].Contains(act)) { eventDic[type].Add(act); } }else { List<Action<T>> list = new List<Action<T>>(); eventDic.Add(type, list); list.Add(act); } } /// <summary> /// 移除事件 /// </summary> /// <param name="type"></param> public static void RemoveEvent(EventType type) { if (eventDic.ContainsKey(type)) { eventDic.Remove(type); } } public static void RemoveEvent(EventType type, Action<T> act) { if (eventDic.ContainsKey(type)) { if (eventDic[type].Contains(act)) { eventDic[type].Remove(act); } } } /// <summary> /// 触发事件 /// </summary> /// <param name="type"></param> /// <param name="data"></param> public static void TriggerEvent(EventType type , T data) { if (eventDic.ContainsKey(type)) { List<Action<T>> list = eventDic[type]; foreach (var callback in list) { callback(data); } } } } public enum EventType { None = 0, Event1 = 1, Event2 = 2, }