Game Development Reference
In-Depth Information
15 if(Item.Value[i] == null)
16 Item.Value.RemoveAt(i);
17 }
18
19 //If items remain in list for this notification, then add this to tmp dictionary
20 if(Item.Value.Count > 0)
21 TmpListeners.Add (Item.Key, Item.Value);
22 }
23
24 //Replace listeners object with new, optimized dictionary
25 Listeners = TmpListeners;
26 }
In essence, the RemoveRedundancies method cycles through every listener for every event type, and
removes any null references where found. Then it regenerates a new Dictionary containing only the
valid entries.
Completing NotificationsManager
We've now seen the core parts of the NotificationsManager—the things that make it work and
be what it is. Critically, this includes the AddListener , PostNotification , RemoveListener , and
RemoveRedundancies methods. Together, these constitute the backbone or infrastructure of the
event-handling system. With just these methods, we can receive and send event notifications
to practically any kind of GameObject and Component in a Unity scene. Let's see the
NotificationsManager class in full, leaving out no code, as shown in Listing 3-13. This class can also
be found in the topic companion files, inside the Chapter03 folder.
Listing 3-13. The Completed NotificationsManager Class (NotificationsManager.cs)
01 //EVENTS MANAGER CLASS - for receiving notifications and notifying listeners
02 //------------------------------------------------
03 using UnityEngine;
04 using System.Collections;
05 using System.Collections.Generic;
06 //------------------------------------------------
07 public class NotificationsManager : MonoBehaviour
08 {
09 //Private variables
10 //------------------------------------------------
11 //Internal reference to all listeners for notifications
12 private Dictionary<string, List<Component>> Listeners = new Dictionary<string,
List<Component>>();
13
14 //Methods
15 //------------------------------------------------
16 //Function to add a listener for an notification to the listeners list
17 public void AddListener(Component Sender, string NotificationName)
18 {
19 //Add listener to dictionary
 
Search WWH ::




Custom Search