- Unity 2017 Game Optimization(Second Edition)
- Chris Dickinson
- 324字
- 2021-07-02 23:21:10
Message cleanup
Since message objects are classes, they will be created dynamically in memory and will be disposed of shortly afterward when the message has been processed and distributed among all listeners. However, as you will learn in Chapter 8, Masterful Memory Management, this will eventually result in a garbage collection, as memory accumulates over time. If our application runs for long enough, it will eventually result in the occasional garbage collection, which is the most common cause of unexpected and sudden CPU performance spikes in Unity applications. Therefore, it is wise to use the Messaging System sparingly and avoid spamming messages too frequently on every update.
The more important clean-up operation to consider is deregistration of delegates if an object needs to be destroyed. If we don't handle this properly, then the Messaging System will hang on to delegate references that prevent objects from being fully destroyed and freed from memory.
Essentially, we will need to pair every AttachListener() call with an appropriate DetachListener() call when the object is destroyed, disabled, or we otherwise decide that we no longer need it to be queried when messages are being sent.
The following method definition in the MessagingSystem class will detach a listener for a specific event:
public bool DetachListener(System.Type type, MessageHandlerDelegate handler) {
if (type == null) {
Debug.Log("MessagingSystem: DetachListener failed due to having no " +
"message type specified");
return false;
}
string msgType = type.Name;
if (!_listenerDict.ContainsKey(type.Name)) {
return false;
}
List<MessageHandlerDelegate> listenerList = _listenerDict[msgType];
if (!listenerList.Contains (handler)) {
return false;
}
listenerList.Remove(handler);
return true;
}
Here is an example usage of the DetachListener() method added to our EnemyManagerWithMessagesComponent class:
void OnDestroy() {
if (MessagingSystem.IsAlive) {
MessagingSystem.Instance.DetachListener(typeof(EnemyCreatedMessage),
this.HandleCreateEnemy);
}
}
Note how this definition makes use of the IsAlive property declared in the SingletonComponent class. This safeguards us against the aforementioned problem of accidentally creating a new MessagingSystem during application shutdown, since we can never guarantee that the Singleton gets destroyed last.
- C及C++程序設計(第4版)
- Spring Cloud Alibaba核心技術與實戰案例
- 深入淺出Windows API程序設計:編程基礎篇
- Rust Essentials(Second Edition)
- Responsive Web Design by Example
- 利用Python進行數據分析(原書第3版)
- 小程序,巧應用:微信小程序開發實戰(第2版)
- Node.js開發指南
- Web App Testing Using Knockout.JS
- Scala Functional Programming Patterns
- OpenCV Android開發實戰
- 百萬在線:大型游戲服務端開發
- 虛擬現實建模與編程(SketchUp+OSG開發技術)
- Android應用開發攻略
- HTML5+CSS3+jQuery Mobile+Bootstrap開發APP從入門到精通(視頻教學版)