I would like to use an editor script to initialize a list of buttons that will perform various actions on objects in my scene. I am wondering how to assign functions to these buttons as varialbes if the functions are defined outside the editor script.
More specifically:
I have a GUI controller script (SomeNeatScript) that performs actions on GameObjects based on GUI events. I would like this script to contain an array of buttons that will each call a different function when clicked. I would like to assign functions to the buttons in an initialization routine that will be called from an Editor Script. I would like the assigned functions to be defined in the GUI script.
Some code:
/* from some editor script */
static function initializeButtons ()
{
var myScript = Selection.activeTransform.GetComponent(SomeNeatScript);
var buttonNames = new Array(
"buttonA",
"buttonB",
"buttonC",
"buttonD"
);
var buttonFunctions = new Array(
myScript.functionA,
myScript.functionB,
myScript.functionC,
myScript.functionD
);
var someButtons = new Array();
for ( var i = 0; i < buttonNames.length; i ++ ) {
var freshButton = new ActionButton(buttonNames_, buttonFunctions*);*_
_*someButtons.Push(freshButton);*_
_*}*_
_*myScript.buttonList = someButtons.ToBuiltin(ActionButton);*_
_*}*_
<em>_/* ActionButton definition */_</em>
_*class ActionButton*_
_*{*_
_*var name : String;*_
_*var actionFunction : Function;*_
_*function ActionButton ( myName : String, myFunc : Function )*_
_*{*_
_*name = myName;*_
_*actionFunction = myFunc;*_
_*}*_
_*}*_
<em>_/* from SomeNeatScript */_</em>
_*var buttonList : ActionButton [];*_
_*function OnGUI ()*_
_*{*_
_*for ( var currentButton : ActionButton in buttonList ) {*_
_*if ( GUI.Button(somePosition, currentButton.name) ) {*_
_*currentButton.actionFunction();*_
_*}*_
_*}*_
_*}*_
_*function functionA ()*_
_*{*_
_*Debug.Log("I am function a");*_
_*}*_
_*function functionB ()*_
_*{*_
_*Debug.Log("I am function b");*_
_*}*_
_*.*_
_*.*_
_*.*_
_*```*_
_*<p>Ideally I would like to reference the names of the assigned functions dynamically (by building Strings based on the button's name) but would settle for the approach outlined above.</p>*_
_*<p>Any help would be greatly appreciated...</p>*_
<em>_<p>** Edit **</p>_</em>
_*<p>As a workaround I can assign the functions in the Start function of my GUI script, but I'd still like to know if it can be done from an editor script. </p>*_
_*<p>And I'd REALLY like to know how to dynamically reference functions by name so I could skip this whole process...</p>*_
Reflection is the most powerful way of getting the methods you want to use. Reflection means for example that you discover members of types, like a method. Then you can invoke that method, given an object and optional parameters.
– StatementReflection can also be used to present the user with a set of functions that could be called, yielding a richer editor.
– Statement