- Unity Game Optimization
- Dr. Davide Aversa Chris Dickinson
- 228字
- 2021-06-24 12:13:05
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.
- 流量的秘密:Google Analytics網站分析與優化技巧(第2版)
- C程序設計簡明教程(第二版)
- Python入門很簡單
- Android 9 Development Cookbook(Third Edition)
- Learning SAP Analytics Cloud
- Web開發的貴族:ASP.NET 3.5+SQL Server 2008
- 實戰低代碼
- 程序是怎樣跑起來的(第3版)
- Haskell Data Analysis Cookbook
- 蘋果的產品設計之道:創建優秀產品、服務和用戶體驗的七個原則
- 打開Go語言之門:入門、實戰與進階
- 3ds Max印象 電視欄目包裝動畫與特效制作
- Python語言科研繪圖與學術圖表繪制從入門到精通
- Java自然語言處理(原書第2版)
- 零基礎學Java(第5版)