- Home /
Accessing a function through its name stored in a string JS
Hi,
I need to access a function in a different script by entering it's name in Editor. Here is my setup so far:
SCRIPT 1: FnCollection.js
//FUNCTION COLLECTION SCRIPT//
private static var instance : FnCollection = null;
static function I() : FnCollection
{
if(instance == null)
{
instance = FindObjectOfType(FnCollection);
}
return instance;
}
function PrintStuff()
{
print("hello");
}
SCRIPT 2: FnRunner
//FUNCTION RUNNER SCRIPT//
var fnToRun: String;
function Start()
{
FnCollection.I().fnToRun();
}
However, it doesn't work because "fnToRun is not a member of FnCollection". This is obvious but how else can I access the function through it's name being retrieved from a string that is editable in the Inspector in the Unity Editor?
I need to have access like this as I plan on putting all my general functions into FnCollection and accessing them when I press buttons and from other scripts.
Thanks
Answer by Peter G · Sep 03, 2011 at 11:28 AM
REEEFLECTION :)
Here's the method you want.
function Start()
{
var myType : Type = FnCollection.I().GetType();
myType.InvokeMember(fnToRun , BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.InvokeMethod , null , FnCollection.I() , args[] );
}
First, get the type of the meted to call. Then call invoke on it. Pass a string with the method name. Pass Binding flags to determine what members to look for. You can usually pass null for the Binder parameter. then pass in the instance you want to call it on, and finally the arguments you want to pass to the function. Null if there are none.
}
Thank you man. I've been looking for this for like 3 hours. I really appreciate your help.