Game Development Reference
In-Depth Information
Listing 10-4. Declaring an Interface in C#
public interface IListener
{
//Event called through listener interface
void OnEventOccured(EVENT_TYPE EType, int Param);
}
At this point, we've defined an interface for a potential event listener. Next, any class can implement
this interface. This means the class guarantees it will implement an OnEventOccured function, as
specified in the IListener interface, as shown in Listing 10-5.
Listing 10-5. Implementing an Interface in C#
public class Listener : MonoBehaviour, IListener
{
//[... other stuff here]
//Implement interface - called on event
public void OnEventOccured(EVENT_TYPE EType, int Param)
{
Debug.Log ("My Event Called");
}
}
Now here, any other class can interface with Listener directly through the IListener interface, without
ever needing to know its true data type . It just needs to know about the IListener interface. Consider
Listings 10-6 and 10-7. These two samples represent two completely separate script files, together
defining a sample event-handling system and a sample Listener, simply for demonstration purposes,
using interfaces. Both of these scripts should be attached to the same object in the scene to test its
functionality in Unity. When you do this, a NotficationsManager will post a notification to a registered
listener on every key press, via interfaces. Notice how this class achieves exactly the same behavior
as the SendMessage and BroadcastMessage functionality we used in Chapter 3, but without the extra
performance cost. Go ahead and try it!
Listing 10-6. NotificationsManager.cs: Defines an Interface and Notifications Manager
//------------------------------------
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
//------------------------------------
public interface IListener
{
//Event called through listener interface
void OnEventOccured(NotificationsManager.EVENT_TYPE EType =
NotificationsManager.EVENT_TYPE.ON_ENEMYDESTROYED, int Param = 0);
}
 
Search WWH ::




Custom Search