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

  • Unity Game Optimization
  • Dr. Davide Aversa Chris Dickinson
  • 326字
  • 2021-06-24 12:13:06

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 garbage collection, as memory accumulates over time. If our application runs for long enough, it will eventually result in 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 cleanup operation to consider is the 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 or 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 class during application shutdown since we can never guarantee that the singleton gets destroyed last.

主站蜘蛛池模板: 宜丰县| 黔西| 拉孜县| 仁布县| 罗定市| 莲花县| 康保县| 绥德县| 西安市| 兴城市| 嘉黎县| 泗洪县| 巫溪县| 邢台市| 漯河市| 和静县| 阿巴嘎旗| 施秉县| 凭祥市| 大丰市| 陇川县| 岐山县| 澄城县| 通海县| 若尔盖县| 虎林市| 南通市| 寿宁县| 山阴县| 商都县| 固安县| 五寨县| 西安市| 措美县| 集安市| 临沧市| 自贡市| 古田县| 凤翔县| 济阳县| 孝义市|