Game Development Reference
In-Depth Information
//Update Game Manager about health change event
GameManager.OnPlayerHealthChange();
}
}
//Private health variable
private int iHealth = 100;
public void Die()
{
//Handle Die Code Here
}
}
This solution, however, is not robust. After all, if even more classes (beyond the
GameManager
) needed
to know about and respond to Player health change events, then we'd have to return to the Player
source code (as we did earlier) and edit the
Health(Set)
function to call even more functions,
propagating the health change event on an
individual
,
per-class
basis. Unfortunately, this problem is
part of a larger and more general one that's in no way restricted to player health change events. The
problem of broadcasting events to objects applies to
all
kinds of objects and
all
kinds of events. For
every kind of event, there could be potentially many objects in need of notification, not just the object
that triggered the event or that was first notified. It is, of course, possible to solve the problem for
each event in a very specific and ad hoc way, as we've done here with the hypothetical
GameManager
class. But in games that handle many events, this would needlessly increase the complexity of our
source code to unmanageable extents. It's easy for event handling to “get out of hand” unless we
take a more disciplined and streamlined approach. This is exactly what we'll do next.
Planning a Dedicated Event-Handling System
The previous section justified the general desirability for taking a more focused and streamlined
approach toward events and event handling in games. In this section, we'll establish the beginnings
of a dedicated and centralized C# event-handling class, which I'll name the
NotificationsManager
.
I'll create the code for this class inside the script file
NotificationsManager.cs
. In general, a game
or scene should have only
one
active instance of this class in memory, and
no more
than one. This
kind of object is known as a Singleton object, a concept considered further in the next chapter. In
short, the NotificationsManager will be singularly responsible for broadcasting
all
events to
all
other
objects that
must
know about those events. In other words, its duty will be to
notify
every object
in the game about every event it must handle, as and when the event happens. In essence, the
NotificationsManager will work as follows (also see Figure
3-2
).