MessageCenter.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class MessageCenter
  6. {
  7. //委托消息传递
  8. public delegate void DelMessageDelivery(object kv);
  9. //消息中心缓存集合
  10. //<string:数据大的分类,DelMessageDelivery数据执行委托>
  11. public static Dictionary<object, DelMessageDelivery> _dicMessages = new Dictionary<object, DelMessageDelivery>();
  12. /// <summary>
  13. ///加消息的监听
  14. /// </summary>
  15. /// <param name="messageType">消息分类</param>
  16. /// <param name="handler">消息委托</param>
  17. public static void AddMsgListener(object messageType, DelMessageDelivery handler)
  18. {
  19. if(!_dicMessages.ContainsKey(messageType))
  20. {
  21. _dicMessages.Add(messageType, null);
  22. }
  23. _dicMessages[messageType] += handler;
  24. }
  25. /// <summary>
  26. /// 移除消息监听
  27. /// </summary>
  28. /// <param name="messageType">消息分类</param>
  29. /// <param name="handler">消息委托</param>
  30. public static void RemoveMsgListener(object messageType, DelMessageDelivery handler)
  31. {
  32. if(_dicMessages.ContainsKey(messageType))
  33. {
  34. _dicMessages[messageType] -= handler;
  35. }
  36. }
  37. /// <summary>
  38. /// 取消所有消息监听
  39. /// </summary>
  40. public static void ClearAllMsgListener()
  41. {
  42. if(_dicMessages != null)
  43. {
  44. _dicMessages.Clear();
  45. }
  46. }
  47. /// <summary>
  48. /// 发送消息
  49. /// </summary>
  50. /// <param name="messageType">消息分类</param>
  51. /// <param name="kv">键值对(对象)</param>
  52. public static void SendMessage(object messageType, object kv)
  53. {
  54. DelMessageDelivery del;
  55. if(_dicMessages.TryGetValue(messageType, out del))
  56. {
  57. if(del != null)
  58. {
  59. //调用委托
  60. del(kv);
  61. }
  62. }
  63. }
  64. }
  65. /// <summary>
  66. /// 配合委托,实现委托数据传递
  67. /// </summary>
  68. public class KeyValuesUpdate
  69. {
  70. //键
  71. private string _Key;
  72. //值
  73. private object _Values;
  74. //只读属性
  75. public string Key
  76. {
  77. get
  78. {
  79. return _Key;
  80. }
  81. }
  82. public object Values
  83. {
  84. get
  85. {
  86. return _Values;
  87. }
  88. }
  89. public KeyValuesUpdate(string key, object valueObj)
  90. {
  91. _Key = key;
  92. _Values = valueObj;
  93. }
  94. }