- Home /
Build variable name using string
For my game I want to load a variable based on a string. The string is made up of standard text plus the ID of the specific object (so I only need one script that can handle actions for lots of objects). The script looks like this (and doesn't function):
string reference = "list" + id;
List<int> thisLevels = OtherStaticScript.reference;
It's pretty obvious to me that it won't work like this, but still it was worth a try.
So is there a way to make this work or a different approach to this issue? Thank you in advance for your help!
Not sure what you're trying to accomplish, but when I hear "get/load/find variable by name using a string" the best answer is usually: you shouldn't want to do that.
This can be accomplished in some cases using Reflection. However, if you find yourself in need of this feature, it's often a sign you're not leveraging the features of the language or following OOP / Unity principles.
Based on your (not nearly thorough enough...) description, I assume you're creating some kind of library of objects at design time, and you'd like to be able to ask for them by name at runtime. This is usually handled by somehow getting those objects into a collection you can search at runtime by looping over the elements & checking against some property like a string name. $$anonymous$$ajor projects use databases for much of this, but it's not necessarily a must, especially for a smaller production.
The best way to put your objects into that searchable collection varies by case, and depends on what kind of objects they are as well as how you're designing / handling / using them. Gonna have to do some research based on your needs. Welcome to the party. ;)
Thank you for your answer. I will try to make it more inline with the 'usual' way then :) .
Thanks everyone for the quick answers, I think I'm gonna stick with doing it the 'right' way then as mentioned before.
Answer by Raresh · Apr 10, 2015 at 11:57 AM
I had a similar issue, what you need is a Dictionary. It is basically a list that has a 'key'. The key can be an int, string, char you name it. With the key you can search for fields in the Dictionary.
Answer by Kriogenic · Apr 10, 2015 at 12:12 PM
I believe you can do something like
string reference = "list" + id;
list<int> thisLevels = OtherStaticScript.GetType().GetProperty(reference).GetValue(OtherStaticScript,null);
I actually don't think this works on arrays or lists but it should be adapted I'm on my phone so hard to write it out complete... GL
I should point out that AlwaysSunny way is correct and you should avoid doing this but its there if you need it.
Your answer
Follow this Question
Related Questions
Change object texture using String [Java] 1 Answer
Separating two strings 1 Answer
convert string to list of lists 1 Answer
Is it possible to name a list by a string variable? 2 Answers
Creating a Token At function 0 Answers