I’m writing a Component Class “A” with a function such as “A.OnComplete()”, I’m writing another Component Class “B” that will Replace “A.OnComplete” with one of B’s functions. I can’t get it to work.
A sample would be great. keeping in mind, That B is NOT a subClass of A, So Virtual functions don’t seem to work here. And that A and B are separate Script Components.
I’m working in Javascript(UnityScript)
Thanks for your help in advance!
2 Answers
2
After some experimentation @senateboy and I found that UnityScript offers limited monkey patching support via assigning functions to:
- untyped variables
- variable of type Function
If running the example below please use the inspector to drop an instance of Script1 into the otherScript slot for Script2:
–Script1.js–
#pragma strict
var functionSlot: Function = Function1;;
function Function1() {
Debug.Log("Function1");
}
function Update () {
if (Input.GetKeyDown(KeyCode.Alpha1)) {
functionSlot = Function1;
}
functionSlot();
}
–Script2.js–
#pragma strict
var otherScript: Script1;
function Function2() {
Debug.Log("Function2");
}
function Update () {
if (Input.GetKeyDown(KeyCode.Alpha2)) {
otherScript.functionSlot = Function2;
}
}
This is cool. Im developing for iOS so from what i know, i need “pragma strict”. But i took your idea, and with pragma Strict, just…
var functionSlot : Function;
And it worked – Thanks a lot!!
The process you describe is called Monkey Patching, while common in Javascript I'm not sure it will work in Unityscript
– KellyThomas