Game Development Reference
In-Depth Information
•
Lines 029-039
: The
Awake
function is responsible for the singleton
functionality, that is, to make the
EventManager
class into a singleton object
that persists across scenes. For more information on persistent singletons,
refer to
Chapter 3
,
Singletons, Statics, GameObjects, and the World
.
•
Lines 046-063
: The
AddListener
method of
EventManager
should be called
by a
Listener
object once for each event for which it should listen. The
method accepts two arguments: the event to listen for (
Event_Type
) and a
reference to the listener object itself (derived from
IListener
), which should
be notified if and when the event happens. The
AddListener
function is
responsible for accessing the
Listeners
dictionary and generating a new
key-value pair to store the connection between the event and the listener.
•
Lines 071-088
: The
PostNotification
function can be called by any object,
whether a listener or not, whenever an event is detected. When called, the
EventManager
cycles all matching entries in the dictionary, searching for all
listeners connected to the current event, and notifies them by invoking the
OnEvent
method through the
IListener
interface.
•
Lines 098-127
: The final methods for the
EventManager
class are responsible
for maintaining data integrity of the
Listeners
structure when a scene
change occurs and the
EventManager
class persists. Although the
EventManager
class persists across scenes, the listener objects themselves
in the
Listeners
variable may not do so. They may get destroyed on scene
changes. If so, scene changes will invalidate some listeners, leaving the
EventManager
with invalid entries. Thus, the
RemoveRedundancies
method
is called to find and eliminate all invalid entries. The
OnLevelWasLoaded
event is invoked automatically by Unity whenever a scene change occurs.
Dictionaries
The great thing about dictionaries is not just their access speed as a
dynamic array (which is comparatively fast) but also the way you
work with them through object types and the array subscript operator.
In a typical array, every element must be accessed by its numerical
and integer index, such as
MyArray[0]
and
MyArray[1]
. But with
dictionaries, the case is different. Specifically, you can access elements
using objects of
EVENT_TYPE
, which represents the key part of the key-
value pair, for example,
MyArray[EVENT_TYPE.HEALTH_CHANGE]
.
For more information on dictionaries, see the official Microsoft
documentation at
http://msdn.microsoft.com/en-us/library/