Game Development Reference
In-Depth Information
//Detect event type
switch(Event_Type)
{
case EVENT_TYPE.HEALTH_CHANGE:
OnHealthChange(Sender, (int)Param);
break;
}
}
For a demonstration on using EventManager , see the events
folder project in the code bundle of this chapter.
Alternative with delegates
Interfaces are an efficient and trim way of implementing an event handling system,
but they are not the only way. We can also use a C# feature, known as delegates.
Essentially, we can create a function and store a reference to it inside a variable.
This variable allows you to treat functions as a reference type variable. That is, with
delegates, you can store references to functions, which can then be used later to
invoke the function itself. Other languages, such as C++, offer a similar behavior
through function pointers. By implementing the event system using delegates, we
eliminate the need for interfaces. Consider the following code sample 4-7, which
is an alternative implementation of EventManager using delegates. Relevant code
changes are highlighted to help illustrate the differences between the interface and
delegate implementations. Apart from minor changes to accommodate the delegate
types, all other functions remained unchanged, as shown here:
001 using UnityEngine;
002 using System.Collections;
003 using System.Collections.Generic;
004 //-----------------------------------------------------------
005 //Enum defining all possible game events
006 //More events should be added to the list
007 public enum EVENT_TYPE {GAME_INIT,
008 GAME_END,
009 AMMO_CHANGE,
010 HEALTH_CHANGE,
011 DEAD};
012 //-----------------------------------------------------------
013 //Singleton EventManager to send events to listeners
014 //Works with delegate implementations
 
Search WWH ::




Custom Search