- Home /
Getting variable name from a string
Hello,
I need to be able to use a xVar by declaring it from a String.
ie
This is pseudo-code
var xVar = 100; var zVar = "xVar"
function X (){
callTheNameOfVarFromZvar.String = 200
}
in the example, xVar would go from 100 to 200, using as name the String in zVar.
I'm not sure if I make much sense, but I'll edit if I find a better way to explain...
Thank you.
Answer by Mike 3 · Dec 06, 2010 at 09:20 PM
You can do this with reflection (See System.Runtime.Reflection in the MSDN docs), but honestly I would skip it for now and use a Dictionary or a HashTable
In both cases, you'd use the string "zVar" to set and get the variable, e.g:
var dictionary = new Dictionary.<String, int>();
dictionary["zVar"] = 200;
Debug.Log(dictionary["zVar"]); //prints out 200
You'll need import System.Collections.Generic; at the top of your file for it to work
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Edit Variables From Game! 1 Answer
Finding the length of a string 2 Answers
GameObject.name to string 2 Answers
PlayerPrefs Question 0 Answers