Game Development Reference
In-Depth Information
subscribers.Clear();
}
This method just adds the delegate you passed to the
manager
class to be added to the
notification list.
Finally, we add a
Broadcast
method that tells the messaging system to let all the sub-
scribers know that something has happened; the following code tells us how to do this:
public void Broadcast()
{
Debug.Log("Broadcast requested, No of Subscribers = " +
subscribers.Count);
foreach (var subscriber in subscribers)
{
subscriber();
}
}
Here, we simply loop through all the subscribers and notify them using their delegates;
very simple!
As you can see, this is just a very basic messenger that when called will tell anyone who is
listening that something has happened; there will be no extra information, no details, just
an event. This is like the fire alarm in your building; when it goes off, you just run—you
don't (usually) ask, you don't question—you just know that when that alarm goes off, you
need to get out of the building!
To finish this
manager
class off, simply create an empty game object in your scene and
add the script to it. There are ways to do that automatically, but I find this way is cleaner
so that you always know what the active agents in the scene are. Later in
Chapter 10
,
The
Battle Begins
, I'll show you a way to create an editor menu option to do this automatically
for you.
Putting this to use is simple. As mentioned before, we need three scripts; we have the
manager
class, so now we need a client and a broadcast agent.
For the broadcast agent, create a C# script named
MessagingClientBroadcast
and
replace its contents with the following code: