Game Development Reference
In-Depth Information
15 //Function name should match event name
16 //Function will be called by the NotificationsManager for every event occurence
17 void EventToListenFor()
18 {
19 //Enters here when event happens
20 }
21 }
The hypothetical class
MyCustomClass
demonstrates
how a GameObject might interact
with an instance of the NotificationsManager. It uses the
Start
function to register with the
NotificationsManager as a Listener for a custom event (note: a class only needs to register for an
event once). And it also implements an additional method whose name matches the event to listen
for. This event will be called automatically by the NotificationsManager every time the event
occurs—this calling behavior is still added to NotificationsManager. See the next section!
Posting Notifications
The
reason
an object registers itself as a listener for an event in the first place is to
receive
notifications when the event actually happens. So far, however, the NotificationsManager only
implements the
AddListener
function, which just builds a list of listeners. The class doesn't (yet)
notify those listeners when events happen. This posting behavior should be implemented now,
through the
NotificationsManager.PostNotification
method. This method should be called by
any and all classes that
cause
or
detect
events. Effectively, these classes say “Ah ha! An event has
happened. I detected it. So now, I'll tell the NotificationsManager. He'll know what to do. He'll pass
on this notification to all registered listeners for this event.” Take a look at Listing 3-10.
Listing 3-10. Posting Notifications to the NotificationsManager
01 //Function to post a notification to a listener
02 public void
PostNotification
(ComponentListener, string NotificationName)
03 {
04 //If no key in dictionary exists, then exit
05
if(!Listeners.ContainsKey(NotificationName))
06 return;
07
08 //Else post notification to all matching listeners
09 foreach(Component Listener in Listeners[NotificationName])
10 Listener.
SendMessage
(NotificationName, Listener,
SendMessageOptions.DontRequireReceiver);
11 }
This is where the “magic” really happens for this class. The following points break it down.
Line 02.
The
PostNotification
function accepts two arguments:
Sender
and
NotificationName
. The
Sender
argument refers to the component
or object that first detected or caused the event, and that notifies the
NotificationsManager. In other words, this argument will be a reference to
the object that invokes or calls the
NotificationsManager.PosNotification
method. The
NotificationsName
argument is a user-defined string indicating
the event that occurred.
1.