Dynamically create variable name from a loop
Let's say I have a list of hats as children in a UI panel, Each hat has a correct name of what it is, such as Tophat, Cowboy, Fedora, etc.
Whether or not their unlocked is stored in bools named boughtHatTophat, etc
How can I make a simple loop to check each variable without individually checking each one?
I would like it to run something like this, in how you can combine strings together with +
foreach (Transform child in hatList)
{
if (boughtHat + child.name == true)
{
child.gameObject.SetActive(true);
}
else
{
child.gameObject.SetActive(false);
}
}
Answer by FortisVenaliter · Jun 08, 2016 at 05:53 PM
You can't. What you can do instead is store the booleans as an array, then match the indices with the hat array.
I ended up doing something similar only using a dictionary ins$$anonymous$$d, using a string as the key and referring it to the proper bool, such as
Dictionary<string, bool> hatDict
hatDict.add(Tophat, boughtHatTophat)
foreach (Transform child in hatList)
{
if (hatDict[child.name] == true)
{
child.gameObject.SetActive(true);
}
else
{
child.gameObject.SetActive(false);
}
}
Thanks for the suggestion!
Your answer
![](https://koobas.hobune.stream/wayback/20220612082522im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Declared variable being returned as null in a method? 0 Answers
Nested For Loop Question 1 Answer
Dictionary creates copy, rather than references 1 Answer
Problem while using several tags in a OnTriggerEnter (Collider other) 0 Answers
Use of unassigned local variable 'startPos' " & " Use of unassigned local variable 'endPos' 1 Answer