unity中的简易消息机制

MsgDispatcher.cs: 

using System;
using System.Collections.Generic;
using UnityEngine;

namespace LJFramework
{
    public class MsgDispatcher : MonoBehaviour
    {
        static Dictionary<string, Action<object>> mRegisteredMsgs = new Dictionary<string, Action<object>>();
        public static void Register(string msgName, Action<object> onMsgRecieved)  //注册消息
        {
            if (!mRegisteredMsgs.ContainsKey(msgName))
            {
                mRegisteredMsgs.Add(msgName, _ => { });
            }
            mRegisteredMsgs[msgName] += onMsgRecieved;
        }
        public static void UnRegisterAll(string msgName)
        {
            mRegisteredMsgs.Remove(msgName);
        }
        public static void UnRegister(string msgName, Action<object> onMsgRecieved)
        {
            if (mRegisteredMsgs.ContainsKey(msgName))
            {
                mRegisteredMsgs[msgName] -= onMsgRecieved;
            }
        }
        public static void Send(string msgName, object data)  //发送消息
        {
            if (mRegisteredMsgs.ContainsKey(msgName))
            {
                mRegisteredMsgs[msgName](data);
            }
        }
    }
}

MsgDispatcherExample.cs: 

using UnityEngine;
namespace LJFramework
{
    public class MsgDispatcherExample
    {

#if UNITY_EDITOR
        [UnityEditor.MenuItem("LJFramework/Examples/3.简易消息机制", false, 3)]
#endif
        private static void MenuClicked()
        {
            MsgDispatcher.UnRegisterAll("消息1");
            MsgDispatcher.Register("消息1", OnMsgRecieved);
            MsgDispatcher.Register("消息1", OnMsgRecieved);

            MsgDispatcher.Send("消息1", "hello world");

            MsgDispatcher.UnRegister("消息1", OnMsgRecieved);

            MsgDispatcher.Send("消息1", "hello");
        }
        static void OnMsgRecieved(object data)
        {
            Debug.LogFormat("消息1:{0}", data);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40323256/article/details/86654255