官术网_书友最值得收藏!

Implementing the Messaging System

Let's define our Messaging System by deriving from the SingletonComponent class and provide a method for objects to register with it:

using System.Collections.Generic;
using UnityEngine;

public class MessagingSystem : SingletonComponent<MessagingSystem> {
public static MessagingSystem Instance {
get { return ((MessagingSystem)_Instance); }
set { _Instance = value; }
}

private Dictionary<string,List<MessageHandlerDelegate>> _listenerDict = new Dictionary<string,List<MessageHandlerDelegate>>();

public bool AttachListener(System.Type type, MessageHandlerDelegate handler) {
if (type == null) {
Debug.Log("MessagingSystem: AttachListener failed due to having no " +
"message type specified");
return false;
}

string msgType = type.Name;
if (!_listenerDict.ContainsKey(msgType)) {
_listenerDict.Add(msgType, new List<MessageHandlerDelegate>());
}

List<MessageHandlerDelegate> listenerList = _listenerDict[msgType];
if (listenerList.Contains(handler)) {
return false; // listener already in list
}

listenerList.Add(handler);
return true;
}
}

The _listenerDict field is a dictionary of strings mapped to lists containing MessageHandlerDelegate. This dictionary organizes our listener delegates into lists by which message type they wish to listen to. Thus, if we know what message type is being sent, then we can quickly retrieve a list of all delegates that have been registered for that message type. We can then iterate through the list, querying each listener to check whether one of them wants to handle it.

The AttachListener() method requires two parameters: a message type in the form of its System.Type and a MessageHandlerDelegate to send the message to when the given message type comes through the system.

主站蜘蛛池模板: 边坝县| 日照市| 绥江县| 安西县| 天等县| 溧水县| 阳朔县| 嘉兴市| 吴堡县| 五莲县| 屯昌县| 兴和县| 远安县| 蓬溪县| 遵化市| 新巴尔虎左旗| 遂宁市| 和硕县| 厦门市| 博客| 吉安县| 大理市| 密云县| 塔河县| 汨罗市| 玛多县| 朝阳区| 哈密市| 福海县| 贵定县| 雷波县| 长沙市| 昌邑市| 康平县| 乌恰县| 新宁县| 兴化市| 海淀区| 五华县| 登封市| 高青县|