Game Development Reference
In-Depth Information
• EventManager : Finally, there's an overarching singleton EventManager object
that persists across levels and is globally accessible. This object effectively
links listeners to posters. It accepts notifications of events sent by posters and
then immediately dispatches the notifications to all appropriate listeners in
the form of events.
Starting event management with interfaces
The first or original entity in the event handling system is the listener—the thing
that should be notified about specific events as and when they happen. Potentially,
a listener could be any kind of object or any kind of class; it simply expects to be
notified about specific events. In short, the listener will need to register itself with
the EventManager as a listener for one or more specific events. Then, when the
event actually occurs, the listener should be notified directly by a function call. So,
technically, the listener raises a type-specificity issue for the EventManager about how
the manager should invoke an event on the listener if the listener could potentially be
an object of any type. Of course, this issue can be worked around, as we've seen, using
either SendMessage or BroadcastMessage . Indeed, there are event handling systems
freely available online, such as NotificationCenter that rely on these functions.
However, in this chapter, we'll avoid them using interfaces and use polymorphism
instead, as both SendMessage and BroadcastMessage rely heavily on reflection
(information on reflection is covered later in Chapter 8 , Customizing the Unity Editor ).
Specifically, we'll create an interface from which all listener objects derive.
More information on the freely available
NotificationCenter (C# version) is available from the
Unity wiki at http://wiki.unity3d.com/index.php?
title=CSharpNotificationCenter .
In C#, an interface is like a hollow abstract base class. Like a class, an interface brings
together a collection of methods and functions into a single template-like unit. But,
unlike a class, an interface only allows you to define function prototypes such as the
name, return type, and arguments for a function. It doesn't let you define a function
body. The reason being that an interface simply defines the total set of functions that
a derived class will have. The derived class may implement the functions however
necessary, and the interface simply exists so that other objects can invoke the
functions via polymorphism without knowing the specific type of each derived class.
This makes interfaces a suitable candidate to create a Listener object. By defining a
Listener interface from which all objects will be derived, every object has the ability
to be a listener for events.
 
Search WWH ::




Custom Search