不知道起名对不对。研究了一下 感觉会有用。
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"; //事件名
public const string START_1 = "Start1"; //
}
触发、
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);
//MessageCenter.Instance.SendMessage(MessageName.START_1);
}
}
}
注册 和 方法的功能
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MessageReceive : MonoBehaviour
{
void Awake()
{
Debug.Log("Awake");
MessageCenter.Instance.RigisterListener(MessageName.START_UP, StartUp); //注册
MessageCenter.Instance.RigisterListener(MessageName.START_1, Start1);
Debug.Log("Awake2");
}
private void StartUp(Message message)
{
Debug.Log("游戏启动");
Debug.Log(message.Name);
Debug.Log(message.Body);
}
private void Start1(Message message)
{
Debug.Log("1");
}
private void OnDestroy()
{
MessageCenter.Instance.RemoveListener(MessageName.START_UP, StartUp);
MessageCenter.Instance.RemoveListener(MessageName.START_1, Start1);
}
}