123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
-
- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
- using System;
- using Newtonsoft.Json.Linq;
- /// <summary>
- /// 2020.11.30 启用事件分发器
- /// </summary>
- public class EventDispatcher : MonoSingleton<EventDispatcher>
- {
- static Dictionary<string, List<Action>> _EventListeners
- = new Dictionary<string, List<Action>>();
- /// <summary>
- /// 注册时间监听
- /// </summary>
- /// <param name="type"></param>
- /// <param name="listener"></param>
- public void AddEventListener(string type, Action ac)
- {
- if (!_EventListeners.ContainsKey(type))
- {
- _EventListeners.Add(type, new List<Action>());
- }
- _EventListeners[type].Add(ac);
- }
- /// <summary>
- /// 设置事件监听
- /// 注意:当次设定值会覆盖之前所有的注册事件而成为唯一事件
- /// </summary>
- /// <param name="type"></param>
- /// <param name="listener"></param>
- public void SetEventListener(string type, Action listener)
- {
- if (!_EventListeners.ContainsKey(type))
- {
- _EventListeners.Add(type, new List<Action>());
- }
- else
- {
- _EventListeners[type].Clear();
- }
- _EventListeners[type].Add(listener);
- }
- /// <summary>
- /// 移除事件监听
- /// </summary>
- /// <param name="type"></param>
- /// <param name="listener"></param>
- public void RemoveEventListener(string type, Action listener)
- {
- if (_EventListeners.ContainsKey(type))
- {
- _EventListeners[type].Remove(listener);
- if (_EventListeners[type].Count <= 0)
- {
- _EventListeners.Remove(type);
- }
- }
- }
- /// <summary>
- /// 清除特定类型事件监听
- /// </summary>
- /// <param name="type"></param>
- public void RemoveAllEventListener(string type)
- {
- if (_EventListeners.ContainsKey(type))
- {
- _EventListeners.Remove(type);
- }
- }
- /// <summary>
- /// 清除全部事件监听
- /// </summary>
- public void ClearAllEventListeners()
- {
- foreach (string type in _EventListeners.Keys)
- {
- _EventListeners[type].Clear();
- }
- _EventListeners.Clear();
- }
- /// <summary>
- /// 发送事件
- /// </summary>
- /// <param name="type"></param>
- /// <param name="_params"></param>
- public void DispatchEvent(string type, object _params1 = null, object _params2 = null)
- {
- if (_EventListeners.ContainsKey(type))
- {
- foreach (Action ac in _EventListeners[type])
- {
- if (ac != null)
- {
- ac();
- }
- }
- }
- }
- }
|