Game Development Reference
In-Depth Information
//Implement interface - called on event
public void OnEventOccured(NotificationsManager.EVENT_TYPE EType = NotificationsManager.
EVENT_TYPE.ON_ENEMYDESTROYED, int Param = 0)
{
Debug.Log ("My Event Called");
}
}
Note A sample project demonstrating interfaces can be found in the topic's companion files at
Chapter10/Interfaces/ .
Delegates
Interfaces simulate polymorphism among classes of different types. Delegates, in contrast, work at
the function or method level, as opposed to the class level. Imagine that you can treat a function
like a variable: you can create a variable and store a reference in it to a function elsewhere, even to a
function in a different class. And then imagine that you could later execute that variable, invoking the
function it references. This is effectively what delegates let you achieve. A delegate is a special object
referencing a function. This means that we can create a NotificationsManager by maintaining an array
of delegates, referencing the functions for many different listener objects. The only standard or rule
the listeners must obey for this to work effectively is that their event functions maintain the same
prototype—that is, has the same argument list and return type. Let's see this in action across two
different script files: one for the NotificationsManager and one for the Listener (see Listings 10-8 and 10-9).
Then give it a test in Unity.
Listing 10-8. NotificationsManager.cs: Defines an Interface and Notifications Manager Using Delegates
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NotificationsManager : MonoBehaviour
{
//Define even types here...
public enum EVENT_TYPE {ON_ENEMYDESTROYED = 0, ON_LEVELRESTARTED = 1, ON_POWERUPCOLLECTED = 2,
ON_KEYPRESS=3};
//Declare listener delegate
public delegate void ListenerDelegate(NotificationsManager.EVENT_TYPE EType, int Param);
//Array of listener delegates
private List<ListenerDelegate> Listeners = new List<ListenerDelegate>();
 
Search WWH ::




Custom Search