Game Development Reference
In-Depth Information
Events
We can describe events as "expected announcements". Imagine you have a bat phone at
your desk; when it rings, you know it's "Batman" on the other end, usually telling you
some trouble has been averted. Events are similar to this pattern where there is a hook;
this is where you can listen for something to happen and then do something with that
event. When it occurs, additionally, through events, you can pass this information to
provide yourself with additional information about what has occurred, as depicted in the
following image:
In the following code, events use delegates to describe how they are going to communic-
ate. It defines the form that communication will take and what information will be passed
when the event is fired:
//Delegate method definition
public delegate void ClickAction();
//Event hook using delegate method signature
public static event ClickAction OnClicked;
Now when an event needs to be initiated in your class, all it needs to do to notify any oth-
er code that is listening to the event is call the event like a method using delegate as
the signature.
Tip
However, what you must be careful about is that no one is listening to the event (no one
has subscribed to it). To do this, you need to check that delegate is not null before
you call it.
Refer to the following code:
Search WWH ::




Custom Search