Key not in Dictionary?
Here's my dictionary:
public Dictionary<string, int> foodWeight = new Dictionary<string, int>();
foodWeight.Add("cake", 1);
and here's where the issue occurs (its at the first foodWeight line):
for (int i = 0; i < foods.foodItems.Length; i++)
{
if (foods.currentHungerPoints >= 1400
&& inventory.weight + foodWeight[foods.foodItems[i]] < 30
&& inventory.size + foodSize[foods.foodItems[i]] < 40)
{
numOfCakes += 1;
inventory.weight += foodWeight[foods.foodItems[i]];
inventory.size += foodSize[foods.foodItems[i]];
Destroy(other.gameObject);
Here is my foods script pertaining to foodItems:
public string[] foodItems; foodItems = new string[2]; foodItems[0] = "cake";
Edit: I've debugged the crap out of this and I still have no clue. It will literally work correctly if I put in 0, but if I make the for loop put in the 0 it conks out! Edit: This is my full error message if that changes anything --> KeyNotFoundException: The given key was not present in the dictionary. System.Collections.Generic.Dictionary`2[System.String,System.Int32].get_Item (System.String key) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:150) InventoryItems.OnTriggerStay (UnityEngine.Collider other) (at Assets/Player/InventoryItems.cs:44)
If you get the error that the key is not in the dictionary, it means whatever key you are passing into the accessor is definitely not there, otherwise you wouldn't get the error. I don't see anything wrong with the posted code, which means the problem might be somewhere else. Perhaps, foodItems[0] = "cake" is called later than the loop. Perhaps something overrides the foodItems[0]. I suggest debugging the script and seeing what is the value of foods.foodItems[i] in each loop iteration.
This is literally so wild! I put Debug.Log(foods.foodItems[i]); before my if statement in my for loop and it literally spits out cake despite it not being able to find cake in the next line. (and I have foodItems[0] = "cake" in my awake function so it can't be that either). Such a conundrum. Thank you for your input!
You know what, it's not foodWeight that doesn't have the "cake" key. It's probably foodSize that doesn't have that key. Edit: you should post the actual error you get.
Answer by Perfecter · Jul 05, 2018 at 10:28 PM
The error is here.
public string[] foodItems;
foodItems = new string[2];
foodItems[0] = "cake";
You allocated array for two strings but assigned only first element. The second element will have default value for string (it is empty string = ""). Then, when you are in your for loop, you gets empty string and trying to get value with this key (="") from foodWeight dictionary. Just set proper foodItems array:
public string[] foodItems;
foodItems = new string[] {"cake"};