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?

Consider using Reflection.

Here’s an answer that should lead you in the right direction.

http://answers.unity3d.com/questions/252903/c-reflection-get-all-public-variables-from-custom.html?viewedQuestions=252797

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.