Dictionary creates copy, rather than references
I'm looking to create a dictionary to use strings to refer to bools reflecting whether or not an item is unlocked.
I thought I could do this with:
Dictionary<string, bool> hatDict = new Dictionary<string, bool>();
//the booleans I want to access already exist elsewhere. I just need a way to reference them from a string
hatDict.Add("Cowboy", Variables.boughtHatCowboy);
hatDict.Add("Cowgirl", Variables.boughtHatCowgirl);
hatDict.Add("Fedora", Variables.boughtHatFedora);
//Then I'd like to use a transforms.name as the key to check the bools of whether or not the item is purchased
foreach (Transform child in hatList)
{
if (hatDict[child.name] == true)
{
child.gameObject.SetActive(true);
}
else
{
child.gameObject.SetActive(false);
}
}
Only thing is when I set up the dictionary it seems to create it's own instance of the bool using the originals value, so when I change the value of the dictionary it doesn't update the original
Any suggestions how to get the dictionary to refer to another var rather than just take the value from it upon declaring?
Answer by FortisVenaliter · Jun 08, 2016 at 08:12 PM
Correct. Bool is a value-type, so it only stores the value, not a reference. Read here for more information. To store it as a reference, you would need to encapsulate it.
Also, it has nothing to do with the dictionary. Any time you set a bool to be equal to another bool, they don't stay linked; rather, the current value of the source is applied into the value of the destination.
Ah I see, and sorry if this is a naive question but how would you go about encapsulating it while still referencing it via string?
You would encapsulate the bool variables into reference types. Then the dictionary would work the same, but you'd have to add editor controls for your new class.
Alternately, get rid of the hard-coded names and just use the dictionary.
Your answer
Follow this Question
Related Questions
Need help to generate a random assortment of 4 buttons - C# 0 Answers
Preventing name duplication in Hierarchy(getting selected GameObject) 1 Answer
How to add a editing option to variables in a script in Inspector? 0 Answers
How to create buttons with script? 0 Answers
Side-scrolling Enemy AI not shooting in the right direction 0 Answers