Game Development Reference
In-Depth Information
The Dictionary has two “dimensions,” based on key-value pairs:
Dictionary<TKey, TValue>
. For
the NotificationsManager
,
I've set the first dimension to be a list of
strings
(for Event Type names),
and the second as
List<
Component
>
(for Listener objects). MonoBehaviour derived components
ultimately descend from type
Component
. I could, of course, have chosen different data types if
I'd wanted, since the
Dictionary
class uses Generics. However, these two types,
strings
and
List<Component>
, will suit our needs, as later sections will show. By using these two types, we can
access
all
listeners as a list for any event of name
N
, with the following code:
//N is an event name: such as "OnHealthChange" or "OnLevelComplete"
List MyListenersList = Listeners[
N
];
Registering As a Listener
So the NotificationsManager now has a private Dictionary member, which makes use of
Generic
types
, and this allows us to maintain a searchable list of potential listeners for events, and the
size of the list can grow and shrink over time. Each listener in the list is specified as being of type
Component
, but thanks to class inheritance and polymorphism, it can really be of
any
type
descended
from
Component, including MonoBehaviour. For more information on polymorphism, see Chapter 10.
In essence, this means our list of listeners can be a wide mix of different types. In this section, we'll
add functionality to the NotificationsManager that lets us
add
a new Listener to the list. If an object
expects to be notified about any event, then it must previously have registered itself as a Listener
with the NotificationsManager. When an object registers itself as a Listener, it's effectively saying,
“Hey, NotificationsManager. I want you to tell me about every occurrence of event X, as and when
it happens!” To achieve this functionality, a new public method
AddListener
can be added to the
NotificationsManager (see Listing 3-8).
Listing 3-8. Adding Listeners to the NotificationsManager
01 //Function to add a listener for an notification to the listeners list
02 public void
AddListener
(Component Listener string NotificationName)
03 {
04 //Add listener to dictionary
05 if(!Listeners.
ContainsKey
(NotificationName))
06 Listeners.Add (NotificationName, new List<Component>());
07
08 //Add object to listener list for this notification
09 Listeners[NotificationName].
Add
(Listener);
10 }
The
AddListener
method accepts two arguments: namely,
Sender
and
NotificationName
. The
Sender
is a Component reference to the object that should become the registered listener. This is the object
that must be notified by the NotificationsManager, if and when the event occurs.
NotificationName
is a string indicating the custom event type for which the Sender is listening. This is a user-defined
string naming the events for our game.