Game Development Reference
In-Depth Information
08 //Cycle through listeners and identify component, and then remove
09 for(int i = Listeners[NotificationName].Count-1; i>=0; i--)
10 {
11 //Check instance ID
12 if(Listeners[NotificationName][i].GetInstanceID() == Sender.GetInstanceID())
13 Listeners[NotificationName].RemoveAt(i); //Matched. Remove from list
14 }
15 }
The RemoveListener function allows the object Sender to remove itself from the Listener list for
the registered event NotificationName . Notice that this function will not unregister the object as a
Listener for all event types, but only for the event type it specifies. The removal process begins in
line 09, with a For loop, and terminates at line 14.
Take care about the deletion of objects from a list during a loop. The loop in line 09 decrements
backward through the list rather than increments forward, because as items are deleted, the list
length or size reduces each time, which can invalidate the iterator I , if it increments.
Removing Redundancies
The RemoveListener method is useful in cases where an object explicitly removes itself as a Listener
from the Dictionary. This is a respectful and tidy way to work, whenever an object no longer wants
event notifications. But the possibility remains that a valid Listener object could be deleted from the
scene without ever calling RemoveListener to remove itself from the Listener Dictionary. If that were
to happen, the associated entries in the Dictionary for that object would remain intact but become
null references and thus be redundant. This could later cause exceptions and errors when methods,
such as PostNotification , iterate through all associated listeners, calling SendMessage . It would be
problematic because we cannot legitimately call SendMessage on null references, since no object
exists to support the function call. For this reason, we'll need to add a new method, which can be
called to cycle through all listeners for all events, and to remove any redundancies if they are found
(see Listing 3-12).
Listing 3-12. Removing All Redundancies from a Dictionary
01 //------------------------------------------------
02 //Function to remove redundant listeners - deleted and removed listeners
03 public void RemoveRedundancies ()
04 {
05 //Create new dictionary
06 Dictionary<string, List<Component>> TmpListeners = new Dictionary<string,
List<Component>>();
07
08 //Cycle through all dictionary entries
09 foreach(KeyValuePair<string, List<Component>> Item in Listeners)
10 {
11 //Cycle through all listener objects in list, remove null objects
12 for(int i = Item.Value.Count-1; i>=0; i--)
13 {
14 //If null, then remove item
 
Search WWH ::




Custom Search