- Home /
dictionary and for each loop and for loop frustrating bug
hey all, hope your all keeping well in these times, i have run into a little snag with my code, i am trying to get a key(S) from a dictionary and on each one of those keys is a component with a bool that i am trying to set true, the code is working as intended but its only setting one of the bool to true not say all 4 if i have 4 in the dictionary
public void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
foreach (var item in groupLookupCache)
{
if (groupLookupCache.TryGetValue(key, out Component value))
{
for (int i = 0; i < key.Length; i++)
{
key[i].GetComponent<SelectedInfo>().isSelected = true;
}
}
}
}
}
this is the latest and greatest i have tried to come up with and to my understanding of the language is that would work but its not its only setting one of the bool to true, any help would be appreciated if someone could please help by pointing me in the right direction it would be ace as i have hit a brick wall and i fear i may have to shelve the whole project if i cannot get it to work as it is one of the main features that i am trying to achieve. please and thank-you!!
brad
Answer by AlirezaSH2004 · May 16, 2020 at 11:01 PM
Hello there. Probably you're trying to apply this to all of the items in "groupLookupCache", so, as you have done this in your code, you've not implemented it in your if statement after the foreach statement. For this to work, you should've written:
public void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
foreach (var item in groupLookupCache)
{
if (groupLookupCache.TryGetValue(item.Key, out Component value))
{
for (int i = 0; i < item.Key.Length; i++)
{
item.Key[i].GetComponent<SelectedInfo>().isSelected = true;
}
}
}
}
}
YW brother. Hope you have some good times with your project.