Game Development Reference
In-Depth Information
This method is short but powerful. It can be broken into two main stages.
1.
Lines 04-06. First, the function searches through all key values (event
types) in the Dictionary, if there are any. The argument NotificationName
specifies the specific event for which to listen for this Listener, and line 05
calls the method Dictionary.ContainsKey to see if this event type already
has an entry in the Dictionary. It will have an entry if there's been a previous
call to NotificationsManager.AddListener , listening for the same event.
Otherwise, an entry for the event will not be present. If there's no existing
entry (no matching key) for the event in the Dictionary (line 06), then a new
entry is created using the Listeners.Add method, and a new Listener list is
instantiated (the value), which will hold all listeners for this event.
2.
Line 09. If there is an existing entry (a matching key) in the Dictionary for the
event, then there will also be a valid and associated Value object. That is,
a List<Component> object, representing the complete list of listeners for this
event. If such a list exists, we don't need to create a new one—we simply
need to add the argument Sender to the end of the existing list, as it becomes
an additional listener for the event.
Note Lines 05 and 06 of Listing 3-8 check the Dictionary for a valid entry, and then retrieves the value of
that entry. However, you can also achieve this same process in just one call using the TryGetValue method
(see http://msdn.microsoft.com/en-us/library/bb347013%28v=vs.110%29.aspx ) .
So, how would a potential Listener object use the AddListener function in practice to register
itself as a Listener for an event with the NotificationsManager? In essence, any script derived
from Component or MonoBehaviour would register itself, as shown in Listing 3-9. Later code
samples in this chapter, and in the topic, will demonstrate in more depth how to work with the
NotificationsManager. We'll be seeing this class in action a lot!
Listing 3-9. Sample Class Registering Itself As a Listener for Event Notifications
01 using UnityEngine;
02 using System.Collections;
03
04 public class MyCustomClass : MonoBehaviour
05 {
06 //Assign this object an instance of the NotificationsManager
07 public NotificationsManager NM = null;
08
09 void Start()
10 {
11 //Add me as a listener for a Custom Event
12 NM.AddListener(this, "EventToListenFor");
13 }
14
 
 
Search WWH ::




Custom Search