- 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.
- Visual FoxPro程序設(shè)計(jì)教程(第3版)
- Hands-On Image Processing with Python
- Linux網(wǎng)絡(luò)程序設(shè)計(jì):基于龍芯平臺(tái)
- TypeScript圖形渲染實(shí)戰(zhàn):基于WebGL的3D架構(gòu)與實(shí)現(xiàn)
- 深入實(shí)踐DDD:以DSL驅(qū)動(dòng)復(fù)雜軟件開發(fā)
- Flask Web開發(fā):基于Python的Web應(yīng)用開發(fā)實(shí)戰(zhàn)(第2版)
- Building Slack Bots
- Julia High Performance(Second Edition)
- Hands-On Robotics Programming with C++
- Practical Maya Programming with Python
- Java程序設(shè)計(jì)入門(第2版)
- HTML5 Canvas核心技術(shù):圖形、動(dòng)畫與游戲開發(fā)
- Python量子計(jì)算實(shí)踐:基于Qiskit和IBM Quantum Experience平臺(tái)
- 零基礎(chǔ)學(xué)C++
- 看漫畫學(xué)Python:有趣、有料、好玩、好用(全彩版)