How to use a variable to call an external script variable?

Hi! This is my first time posting here but I’ve been lurking for a month or so. Thanks to everyone for making this an awesome resource for zipping through Unity.

On to the question. Its hard for me to sum it up so please pardon the above title. What I am trying to do is use a particular unknown string to set the value on a static variable. Example.

var someString = "Car"; //name of the variable in the other script 
var someFloatValue = 5.0; //point value to assign to the above variable.  

..... 
someFloatValue += 1234; 
otherScript.{someString} = someFloatValue;

To give additional clarification if needed, the other script would look something like this…

var Car = 0.0; 
var Bike = 0.0; 
var Bob = 0.0;

And so on. Any assistance with this would be greatly appreciated! Thanks!

This requires a programming technique called Reflection and is in general considered to be bad practice unless necessary.

It is most definitely possible in Unity’s Javascript, but not recommended. Why do you wish to do this? perhaps we can come up with a better approach.

I’m all for exploring other avenues.

The intended purpose is that I will be sharing this script on several objects but each object needs to update a specific variable in another script. I could use a switch case based on a string comparison but I figured I’d save a step and expose it so I could assign it directly.

The simplest method would be to get a reference to the file containing the variable and then just setting it as normal.

I.e.

var myScript : MyClass;

function Start()
{
  var obj :GameObject = GameObject.Find("LevelGlobals");
  myScript = obj.GetComponent(MyClass);
}

function UpdateSomeVar(to : int)
{
  myScript.someVar = to;
}

If you want to create a datablock that is shared amongst all instances of the class, then it is even simpler. Don’t. Just create the variables as STATIC and then set the variables inside the same script. It will then instantly reflect in all instances of the script.

The other option, is to declare the variables as static and then update the CLASS inside your code.

For example, create a file named Globals.js and then say

static var someFloatValue : float = 0;

and then inside any other script in your project, just say

Globals.someFloatValue = 10;

The same is true for any filename. If the variable is static, just call [filename].[variablename]