- Home /
String + Variable to retrieve a variable?
Here's a quick Example of what I would like to do.
string name1 = "John";
string name2 = "Mark";
int personNum = 1;
Debug.Log(this["name"+personNum]); // Prints John
this["name"+2] = "Mike"; // Changes Mark to Mike
Debug.Log(this["name"+2]); // Prints Mike
//John
//Mike
So as you can see, I'm wondering if it's possible to form variables using strings/variables/ints for temporary use (setting or getting variables). This works in other languages and obviously 'this["variable string"] is not the correct C# syntax.
Note: I'm only trying to access pre-defined variables using this method, not create them.
Thanks.
Answer by DaveA · Oct 10, 2012 at 09:42 PM
You could also create a Hash list and use the variable names as the keys.
That's true. But then the hash won't appear on the object script properties right?
Also I'm trying to store a bunch of sound effects in variables (through the public properties) and be able to easily access any with a string. Can't do that with arrays, and hash tables won't show up on property panel.
Thanks for the info though!
You can easily access sound effects in arrays. I would strongly recommend not using reflection and strings; it's quite slow and prone to error. If you want to use something "string-like" ins$$anonymous$$d of numbers, use an enum.
Yeah thanks, I was just hoping for a easy way to add sound effects to a script via the property manager, and then be able to access them with simple strings (without having to manually place them in hashtables, arrays, etc).
Oh well, thanks for the info. I'll use reflection for $$anonymous$$or things, and probably hash tables or arrays for larger, more time consu$$anonymous$$g processes.
Answer by Juice-Tin · Oct 10, 2012 at 09:16 PM
Aha! Found it myself on some C# forums.
(string)this.GetType().GetField("name"+1).GetValue(this);
this returns the string variable called name1;
I'm actually impressed that you found the reflection way ;) $$anonymous$$eep in $$anonymous$$d that reflection is slow and should be avoided if possible since it breaks most OOP rules. Usually there are better ways of doing what you want to do.
The simplest way is to use an array
public string[] name;
Btw: the variable name "name" could be a problem since "name" is already a property of Component.
Your answer

Follow this Question
Related Questions
Edit Variables From Game! 1 Answer
Label dots in between numbers (currency formatting) 2 Answers
variables as GUI 1 Answer
Optimizing OnGUI 1 Answer
String as Variable name 0 Answers