123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using XRTool.Util;
- public class MsgHandler : MonoBehaviour
- {
- public delegate void DelMsgHandler(Msg msg);
- private static Dictionary<string, DelMsgHandler> mDicMsgs = new Dictionary<string, DelMsgHandler>();
- /// <summary>
- /// 添加监听者
- /// </summary>
- /// <param name="msgType"></param>
- /// <param name="handler"></param>
- public static void AddListener(string msgType, DelMsgHandler handler)
- {
- try
- {
- //判空
- if (mDicMsgs == null) mDicMsgs = new Dictionary<string, DelMsgHandler>();
- if (!mDicMsgs.ContainsKey(msgType)) mDicMsgs.Add(msgType, null);
- mDicMsgs[msgType] += handler;
- }
- catch
- {
- TimerMgr.Instance.CreateTimer(()=> {
- handler.Invoke(new Msg("", null));
- },1);
- // mDicMsgs[msgType] += handler;
- }
- //增加监听
- }
- /// <summary>
- /// 去除对参数handler的监听
- /// </summary>
- /// <param name="msgType">消息类型</param>
- /// <param name="handler">被监听方法</param>
- public static void RemoveListener(string msgType, DelMsgHandler handler)
- {
- if (mDicMsgs != null && mDicMsgs.ContainsKey(msgType)) mDicMsgs[msgType] -= handler;
- }
-
- /// <summary>
- /// 清除所有的监听者
- /// </summary>
- public static void ClearAllListeners()
- {
- if (mDicMsgs != null) mDicMsgs.Clear();
- }
- /// <summary>
- /// 分发消息
- /// </summary>
- /// <param name="msgType">消息类型</param>
- /// <param name="msg">分发的内容</param>
- public static void SendMsg(string msgType, Msg msg)
- {
- DelMsgHandler handler;
- if (mDicMsgs != null && mDicMsgs.TryGetValue(msgType, out handler))
- {
- if (handler != null)
- handler(msg);
- }
- }
- /// <summary>
- /// 群发消息
- /// </summary>
- /// <param name="msg">消息内容</param>
- public static void AllSendMsg(Msg msg)
- {
- foreach (var item in mDicMsgs)
- {
- item.Value(msg);
- }
- }
- }
- public class Msg
- {
- public string Key { get; private set; }
- public object Value { get; private set; }
- public Msg(string key, object value)
- {
- this.Key = key;
- this.Value = value;
- }
- }
|