Game Development Reference
In-Depth Information
Classified intel
In this section, we have used the
delegate
and
event
functions to set the event and
event listener. The basic idea of the
delegate
and
event
functions in C# is that we can
call the functions from other scripts by having it to listen to the event function. We do this
by first creating the
delegate
function as follows:
public delegate void OnDelegateFunction();
Then, we create a
static
event of the
delegate
function that we just created:
public static event OnDelegateFunction myEvent;
We use
static
because we want to have the same event for every listener. This way, we
can have multiple listeners listen to the same event. Next, we trigger this event by calling
myEvent();
.
Then, we use the plus (
+
) sign to add the function to the event and use the negative (
-
) sign
to remove it from the event that is calling.
For a Unity JavaScript user, if we go to the
Chapter7/Scripts/Javascript
folder
in the
Project
view, we will see the
JSDelegate
script there. Double-click on this script
to open it and you will see the following code:
import System.Collections.Generic;
class JSDelegate {
private var _callbacks : List.<Function> = new
List.<Function>();
function Add (callback : Function) : void {
_callbacks.Add(callback);
}
function Remove (callback : Function) : void {
_callbacks.Remove(callback);
}
function Clear () : void {
_callbacks.Clear();
}
function Invoke () : void {