using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 消息类
/// </summary>
public class Message
{
public string Name //发送消息的名称
{
get;
private set;
}
public object Body //消息主体
{
get;
private set;
}
public Message(string name, object body)
{
Name = name;
Body = body;
}
}
/// <summary>
/// 消息中心
/// </summary>
public class MessageCenter {
public delegate void messageDelHandle(Message message);
private static MessageCenter instance;
public static MessageCenter Instance
{
get
{
if (instance==null)
{
instance = new MessageCenter();
}
return instance;
}
}
private Dictionary<string, messageDelHandle> messageMap = new Dictionary<string, messageDelHandle>();
/// <summary>
/// 注册监听
/// </summary>
public void RigisterListener(string messageName,messageDelHandle handle)
{
if (handle == null) return;
if(!messageMap.ContainsKey(messageName))
{
messageMap.Add(messageName, handle);
}
}
/// <summary>
/// 移除监听
/// </summary>
public void RemoveListener(string messageName,messageDelHandle handle)
{
if (!messageMap.ContainsKey(messageName))
return;
messageMap[messageName] -= handle;
if (messageMap[messageName] == null)
{
messageMap.Remove(messageName);
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="messageName">消息名称 </param>
/// <param name="body"> 发送消息主体 </param>
public void SendMessage(string messageName,object body = null)
{
if (!messageMap.ContainsKey(messageName))
return;
messageDelHandle handle;
messageMap.TryGetValue(messageName, out handle);
if(handle!=null)
{
handle(new Message(messageName, body));
}
}
}
/// <summary>
/// 发送的消息名
/// </summary>
public class MessageName {
public const string START_UP = "StartUp"; //游戏启动
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MessageSend : MonoBehaviour {
void Update ()
{
if (Input.GetMouseButtonDown(0))
{
MessageCenter.Instance.SendMessage(MessageName.START_UP);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MessageReceive : MonoBehaviour {
void Awake ()
{
MessageCenter.Instance.RigisterListener(MessageName.START_UP, StartUp);
}
private void StartUp(Message message)
{
Debug.Log("游戏启动");
}
private void OnDestroy()
{
MessageCenter.Instance.RemoveListener(MessageName.START_UP,StartUp);
}
}
unity 消息发送处理机制
最新推荐文章于 2024-06-10 10:38:55 发布