- Home /
Match name to variable name?
var test1 = 10;
var test2 = 4;
var test3 = 30;
function printValue ( value : int )
{
Debug.Log( value );
}
Let's say I have the code above in one script, and I want to pass one of those variables to that function from an external script. Using the external script, I have the name of the variable I want to pass as a string (e.g., "test2"). Can I get the variable that matches that string, so I can pass that to the function?
Unfortunately that cannot be done as far as i know. However, there are alternatives. You can store the variables in an array, and use their position inside the array as an argument.
You don't need to use a string; you can try using static functions or access public variables and functions through a component gameObject.GetComponent("Script").printValue(gameObject.GetComponent("Script").test1));
Answer by Dave-Carlile · Feb 20, 2013 at 02:10 PM
Consider using Reflection.
Here's an answer that should lead you in the right direction.
I don't know how much of this applies to Javascript in Unity.
Another possibility, and I would only recommend this if you have very few variables you're dealing with, and it's kind of hacky... And I'm doing this in C#, but it should be easy to convert to Javascript...
int VariableValueFromName(string name)
{
if (name == "test1") return test1;
if (name == "test2") return test2;
if (name == "test3") return test3;
return 0; // or throw an exception since the name isn't recognized
}
Also, rather than having individual variables, you could use a Dictionary to store values indexed by a string. Again, I'm not completely sure if the Dictionary
class is available in Javascript.
Thanks for the info. I'd thought about these options. I guess the important thing is you just confirmed for me that it isn't really something that can be done neatly.
I think I'll change my approach in my game to make it possible to send the var data directly.