Unity 消息机制
最近有新项目需要和同事合作开发,他做UI 我做网络层,做着做着发现
如果我们要相对独立完成自己的开发任务,那我们的代码耦合得减少,不然
一个人代码有大改的时候,另一个人也要进行大幅修改,这样不便于后期开发维护。
然后做了一个简单的消息机制。
总的来说是用了一个委托的方式解决的
这是消息管理, 负责添加\删除 监听者,和分发消息的
using System.Collections.Generic; public class MsgHandler { 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) { //判空 if (mDicMsgs == null) mDicMsgs = new Dictionary<string, DelMsgHandler>(); if (!mDicMsgs.ContainsKey(msgType)) mDicMsgs.Add(msgType, null); //增加监听 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; } }
这是监听类, 负责监听
public class MsgReceive : MonoBehaviour { private void Awake() { MsgHandler.AddListener("MsgReceive", HandleMsg); } private void HandleMsg(Msg msg) { } private void OnDestroy() { MsgHandler.RemoveListener("MsgReceive", HandleMsg); } }