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

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. Hence, 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 MessageHandlerDelegate to send the message to when the given message type comes through the system.

主站蜘蛛池模板: 万年县| 台南市| 延安市| 额济纳旗| 元江| 宣汉县| 晋江市| 册亨县| 清水河县| 贵德县| 南投县| 常德市| 壤塘县| 兴国县| 河西区| 泰顺县| 红桥区| 祥云县| 凤城市| 蓬溪县| 光泽县| 泾川县| 汉寿县| 西峡县| 马尔康县| 邛崃市| 石台县| 陇西县| 南丰县| 启东市| 曲周县| 元江| 云南省| 新乡市| 壶关县| 封丘县| 鄂尔多斯市| 定兴县| 岳西县| 永济市| 凤台县|