- I would like to expose a static public delegate in my JS script file. How can I do this?
- How do I add handlers to the delegate?
I'd basically want to be able to do the following (C#) but for JS:
public static Action Handler;
void OnEnable()
{
Handler += Foo;
}
void OnDisable()
{
Handler -= Foo;
}
void Foo()
{
// Some interesting code...
}
1 Answer
1
I have only come up with a workaround. I am still curious to see if there is any easier way of going about.
JSDelegate.js
class JSDelegate
{
// Can't use List.<T> - Compile error:
// BCE0015: Node 'callable()' has not been correctly processed.
// private var callbacks : List.<function()> = new List.<function()>();
// So we have to use an ArrayList instead.
private var callbacks : ArrayList = new ArrayList();
function Add(callback : function())
{
callbacks.Add(callback);
}
function Remove(callback : function())
{
callbacks.Remove(callback);
}
function Invoke()
{
for (var callback : function() in callbacks)
callback();
}
}
Example1.js
static var Handler : JSDelegate = new JSDelegate();
function OnEnable()
{
Handler.Add(Bar);
}
function OnDisable()
{
Handler.Remove(Bar);
}
function Bar()
{
Debug.Log("Bar called!");
}
Example2.js
function Update()
{
if (Input.GetKeyDown(KeyCode.E))
Example1.Handler.Invoke();
}