replace instance method after instance is created.

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!

The process you describe is called Monkey Patching, while common in Javascript I'm not sure it will work in Unityscript

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;
	}
}

In C#, this can be achieved with delegates. public class A{ private System.Action RealMethod; /* ^ is shorthand for private delegate void aNamedDelegate(); private aNamedDelegate RealMethod; */ void Function1(){ Debug.Log("function1"); } void Function2(){ Debug.Log("function2"); } void Update(){ RealMethod = Function1; RealMethod(); // output: function1 RealMethod = Function2; RealMethod(); // output: function2 } }

Bookmark added! thanks again

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!!

Excellent! Great to see that it's possible. I have fleshed out my example to demonstrate strong typing and cross class patching.