MsgHandler.cs 2.1 KB

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