- Unity 2017 Game Optimization(Second Edition)
- Chris Dickinson
- 228字
- 2021-07-02 23:21:09
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.
- Web前端開發技術:HTML、CSS、JavaScript(第3版)
- Cocos2D-X權威指南(第2版)
- C#完全自學教程
- 編寫高質量代碼:改善Python程序的91個建議
- Python從入門到精通(精粹版)
- Functional Programming in JavaScript
- 從Excel到Python:用Python輕松處理Excel數據(第2版)
- 數據科學中的實用統計學(第2版)
- Microsoft HoloLens By Example
- C語言程序設計教程
- 川哥教你Spring Boot 2實戰
- Neo4j權威指南 (圖數據庫技術叢書)
- 前端程序員面試筆試真題與解析
- Java EE應用開發及實訓
- Mastering Android Application Development