MsgHandler.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using XRTool.Util;
  5. public class MsgHandler : MonoBehaviour
  6. {
  7. public delegate void DelMsgHandler(Msg msg);
  8. private static Dictionary<string, DelMsgHandler> mDicMsgs = new Dictionary<string, DelMsgHandler>();
  9. /// <summary>
  10. /// 添加监听者
  11. /// </summary>
  12. /// <param name="msgType"></param>
  13. /// <param name="handler"></param>
  14. public static void AddListener(string msgType, DelMsgHandler handler)
  15. {
  16. try
  17. {
  18. //判空
  19. if (mDicMsgs == null) mDicMsgs = new Dictionary<string, DelMsgHandler>();
  20. if (!mDicMsgs.ContainsKey(msgType)) mDicMsgs.Add(msgType, null);
  21. mDicMsgs[msgType] += handler;
  22. }
  23. catch
  24. {
  25. TimerMgr.Instance.CreateTimer(()=> {
  26. handler.Invoke(new Msg("", null));
  27. },1);
  28. // mDicMsgs[msgType] += handler;
  29. }
  30. //增加监听
  31. }
  32. /// <summary>
  33. /// 去除对参数handler的监听
  34. /// </summary>
  35. /// <param name="msgType">消息类型</param>
  36. /// <param name="handler">被监听方法</param>
  37. public static void RemoveListener(string msgType, DelMsgHandler handler)
  38. {
  39. if (mDicMsgs != null && mDicMsgs.ContainsKey(msgType)) mDicMsgs[msgType] -= handler;
  40. }
  41. /// <summary>
  42. /// 清除所有的监听者
  43. /// </summary>
  44. public static void ClearAllListeners()
  45. {
  46. if (mDicMsgs != null) mDicMsgs.Clear();
  47. }
  48. /// <summary>
  49. /// 分发消息
  50. /// </summary>
  51. /// <param name="msgType">消息类型</param>
  52. /// <param name="msg">分发的内容</param>
  53. public static void SendMsg(string msgType, Msg msg)
  54. {
  55. DelMsgHandler handler;
  56. if (mDicMsgs != null && mDicMsgs.TryGetValue(msgType, out handler))
  57. {
  58. if (handler != null)
  59. handler(msg);
  60. }
  61. }
  62. /// <summary>
  63. /// 群发消息
  64. /// </summary>
  65. /// <param name="msg">消息内容</param>
  66. public static void AllSendMsg(Msg msg)
  67. {
  68. foreach (var item in mDicMsgs)
  69. {
  70. item.Value(msg);
  71. }
  72. }
  73. }
  74. public class Msg
  75. {
  76. public string Key { get; private set; }
  77. public object Value { get; private set; }
  78. public Msg(string key, object value)
  79. {
  80. this.Key = key;
  81. this.Value = value;
  82. }
  83. }