Game Development Reference
In-Depth Information
Using EventManager
Now, let's see how to put the EventManager class to work in a practical context from
the perspective of listeners and posters in a single scene. First, to listen for an event
(any event) a listener must register itself with the EventManager singleton instance.
Typically, this will happen once and at the earliest opportunity, such as the Start
function. Do not use the Awake function; this is reserved for an object's internal
initialization as opposed to the functionality that reaches out beyond the current
object to the states and setup of others. See the following code sample 4-6 and notice
that it relies on the Instance static property to retrieve a reference to the active
EventManager singleton:
//Called at start-up
void Start()
{
//Add myself as listener for health change events
EventManager.Instance.AddListener(EVENT_TYPE.HEALTH_CHANGE, this);
}
Having registered listeners for one or more events, objects can then post notifications
to EventManager as events are detected, as shown in the following code sample 4-7:
public int Health
{
get{return _health;}
set
{
//Clamp health between 0-100
_health = Mathf.Clamp(value, 0, 100);
//Post notification - health has been changed
EventManager.Instance.PostNotification(EVENT_TYPE.
HEALTH_CHANGE, this, _health);
}
}
Finally, after a notification is posted for an event, all the associated listeners are
updated automatically through EventManager . Specifically, EventManager will call
the OnEvent function of each listener, giving listeners the opportunity to parse event
data and respond where needed, as shown in the following code sample 4-8:
//Called when events happen
public void OnEvent(EVENT_TYPE Event_Type, Component Sender,
object Param = null)
{
 
Search WWH ::




Custom Search