在之前的博客中曾经写过一篇《Unity-基于面向对象多态特征的消息收发机制》,但是继承的层次比较多,不便于初学者的学习和使用,此篇博客是基于委托的消息收发机制。
制定事件码
事件码要对应于后面的不同的方法 事件码和方法是一一对应的 不能重复 是执行的方法的唯一标识 相当于方法的身份证
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 对于不同的模块儿使用了不同段的数字 便于管理和操作
/// </summary>
public class EventCode
{
/// <summary>
/// UI
/// </summary>
public const int UI_StartPanelActive = 10000;
/// <summary>
/// Net
/// </summary>
public const int Net_Send = 20000;
}
消息中心
消息中心作用是对事件的注册 执行和移除的处理
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MessageCenter : MonoBehaviour {
public static MessageCenter Instance;
/// <summary>
/// 用于储存事件码和
/// </summary>
private Dictionary<int, Action<object>> messageCenterDict = new Dictionary<int, Action<object>>();
private void Awake()
{
Instance = this;
}
public void Dispatcher(int eventCode,object message)
{
if (messageCenterDict.ContainsKey(eventCode))
{
messageCenterDict[eventCode].Invoke(message);
}
}
/// <summary>
/// 注册事件
/// </summary>
public void AddListener(int eventCode, Action<object> action)
{
if (!messageCenterDict.ContainsKey(eventCode))
{
messageCenterDict.Add(eventCode, action);
}
}
/// <summary>
/// 移除监听事件
/// </summary>
/// <param name="subcode"></param>
public void RemoveAddlistener(int eventCode)
{
if (messageCenterDict.ContainsKey(eventCode))
{
messageCenterDict.Remove(eventCode);
}
}
}
测试代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIButton : MonoBehaviour {
// Use this for initialization
void Start () {
//注册开始面板的状态的事件
MessageCenter.Instance.AddListener(EventCode.UI_StartPanelActive, Test);
}
public void Test(object num)
{
//这里通过打印数字来展示功能 没有真的操作开始面板 Demo中也没有开始面板
Debug.Log((int)num);
}
private void OnDestroy()
{
//取消对开始面板的监听
MessageCenter.Instance.RemoveAddlistener(EventCode.UI_StartPanelActive);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoomButton : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//触发事件
//模式操作开始面板
if (Input.GetMouseButtonDown(0))
{
MessageCenter.Instance.Dispatcher(EventCode.UI_StartPanelActive, 2);
}
}
}