Game Development Reference
In-Depth Information
Listing 3-5. Autogenerated Class for NotificationsManager, Descended from MonoBehaviour
using UnityEngine;
using System.Collections;
public class NotificationsManager : MonoBehaviour
{
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
In addition to being descended from
MonoBehaviour
, all newly generated classes come with
predeclared
Start
and
Update
functions. The
Start
function is called automatically once at object
creation (after the
Awake
function), and the
Update
function is called automatically once per frame,
provided
the
GameObject
is active—that is, provided the object has its
active
member set to true.
By default, all GameObjects are active unless they are explicitly deactivated with a call to
GameObject.SetActive
. For the
NotificationsManager
class, we can safely delete both the
Start
and
Update
functions, as we'll never need them.
Tip
If your class never needs or uses a function, such as
Start
and
Update
, then remove them from the
class. This makes your code neater generally, and there are even marginal performance improvements to
be gained.
Note
More information on MonoBehaviour can be found at the online Unity documentation at
Keeping Track of Notifications with .NET Dictionaries
Thinking carefully about the
NotificationsManager
class we know that (a) Posters must tell the
NotificationsManager when an event occurs, and (b) when told about an event, the NotificationsManager
should notify all registered Listeners
for that event
. This entails that the Notifications Manager
must internally maintain a list of all listeners that should be notified for an event when it happens.
These listeners should be organized into lists by
event type
. That is, for any event type (such as
OnPlayerHealthChange
)
there could be none, one, or more listeners
. Regardless, however many or
however few objects are listening for an event, it's the responsibility of the NotificationsManager to notify
them all whenever that event happens. And so ultimately our class has two main technical requirements:
we must maintain a list of
events
, and for each type we must maintain a list of associated
listeners
.