- Home /
call variable from string?
Hi everyone, i'm new to unity and javascript. since now, sorry for my bad english ;) .
i've the following script (called inventory) that's just a reference for the objects
static var object1 = 0;
static var object2 = 0;
static var object3 = 0;
and another script where i've an integer input (1,2,3). i need to know how to modify inventory.variables from this script something like
inventory.(object+input) = 1;
there's a way to call a variable from a string + an integer value? or just a string?
thanks everyone :)
Answer by Fabkins · Jan 14, 2014 at 08:32 PM
In short you cannot do this in this fashion. What you are probably needing is either an array or hashtable.
This is an example of using an array:
var myobject = [10,11,12];
myobject[2]=5; // NOTE that the index of 2 is the the THIRD value
Debug.Log(myobject[0]);
Debug.Log(myobject[1]);
Debug.Log(myobject[2]);
This is an example of using a Hashtable:
var myrefs = new Hashtable();
myrefs["object1"]=0;
myrefs["object2"]=0;
myrefs["object3"]=0;
var lookupString: String;
var indexNumber=2;
lookupString="object"+indexNumber.ToString();
myrefs[lookupString]=3;
Debug.Log(myrefs["object1"]);
Debug.Log(myrefs["object2"]);
Debug.Log(myrefs["object3"]);
Read up on Arrays and Hashes on:
http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use?
Note that Unity has two types of arrays and its sometimes confusing so be aware
Following this idea you could go for a dictionary which would use a similar pattern as you are showing in your example:
var template = "object";
var dict = new Dictionary.<string,int>();
var tempString = template + input.ToString();
dict[tempString] = value;
but I don't really see the need of complexity when array would make it easy.
I agree, although I added my post to include the use of a Hash, if you are trying to reference something by an integer index you should really be using an array.
thanks a lot, but what if i have static var myobject_one static var myobject_two ? what would be the best way?
Please refer to the first line of answer. You cannot reference different variables by their variable names. That's what arrays, hash, dictionaries were design for.
Your answer
![](https://koobas.hobune.stream/wayback/20220613130438im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Static Variables 1 Answer
Accessing a js static var from a c# script 1 Answer
Cannot use Static var/ Unknown Idientifier 1 Answer
multiple instantiate object script help 2 Answers
On Clicked, On Released GUI Button ? 2 Answers