So, I have a dictionary called Potions. I need to check if a key in potions has the same name as an object passed as an argument. Now I’m able to do that but I can’t figure out how to add a value to that particular key if the item object and the key have the same name. This code works fine for the first instance of an object. But when I add another instance object with the same name as a key, I get a key not found exception. I understand that the 2 objects wont be the same.How can I extract the object reference inside the dictionary? Or is there another way?
public static void addItem(Potion item)
{
if (Potions.Count >0)
{
foreach(KeyValuePair<Potion,int> pair in Potions)
{
if (pair.Key.itemName == item.itemName)
{
containsItem = true;
}
}
if (containsItem)
{
Potions[item] += 1;
Debug.Log (Potions[item]);
containsItem = false;
}
else
{
Potions.Add(item,1);
}
}
else
{
Potions.Add (item,1);
}
foreach(KeyValuePair<Potion,int> pair in Potions)
{
Debug.Log (pair.Key.itemName + " : " + pair.Value);
}
}
You can override
EqualsandGetHashCode, but that might have other implications. Instead, you can use anIEqualityComparerwhen you create the dictionary, like so: