Game Development Reference
In-Depth Information
Note
It's always a good idea to clean up after yourself and unsubscribe from the events when
you no longer need them, as shown in the preceding code, using the -= syntax.
This is a very simple example, but you could imagine exposing an event for when an en-
emy is destroyed and hooking your score system into it so that the score is incremented
every time an enemy dies.
A better way is to write a separate method to call when you need to trigger the event; refer
to the following code. In this way, you don't have the preceding code repeated throughout:
//Safe method for calling the event
void Clicked()
{
//Trigger the event delegate if there is a subscriber
if (OnClicked != null)
{
OnClicked();
}
}
Now, all you have to do whenever the event needs to be fired is call the Clicked method
that is shown in the preceding code, which is always safe and won't crash if there are no
subscribers.
As a help, this code is the template I always use when creating an event. To simplify its
creation, all you have to do to use it each time is change the name, and if necessary, the
delegate signature if you need additional parameters; the following code will tell you how
to do this:
//Logging template to send a string/report every time
something //happens
public delegate void LogMessage(string message);
public static event LogMessage Log;
void OnLog(string message)
{
if (Log != null)
Search WWH ::




Custom Search