Hopefully my code explains what I’m trying to do. Yet if I can’t substitute in strings for the function name…what is my alternative?
#pragma strict
var objWithScript : GameObject;
var scriptName : String = "Script";
var functionName : String = "Do This";
function Start () {
}
function Update () {
}
function OnClick ()
{
objWithScript.GetComponent(scriptName).functionName();
}
Use a dictionary. Since your method does not take any parameter and doe snot return anything I guess it should go as such (not sure in Js…):
var myDictionary = new Dictionary.<string,Action>();
myDictionary["FunctionName"] = FunctionName;
then you call it:
objWithScript.myDictionary[scriptName]();
What you wish is called “Reflection” in programming. Use MonoBehaviour.Invoke()
with scriptName as Type
instead of String
(remove also the quotation marks).
(objWithScript.GetComponent(scriptName) as MonoBehaviour).Invoke(functionName,0.01);