Hi,
well I have been making a Inventory System, and I have all time “The given key was not present in the dictionary.” error, when I test it:
using UnityEngine;
using System.Collections;
//ItemDataBase
public class ItemScript : MonoBehaviour {
private GameObject LoadItemPrefab(string name) {
return (GameObject)Resources.Load ("prefabs/Items/"+name);
}
private Texture LoadItemTex(string name) {
return (Texture)Resources.Load ("textures/Items/"+name);
}
void Start() {
Inventory inv = new Inventory();
InventoryItem preset;
preset = new InventoryItem();
preset.id = 1;
preset.itemname = "Ring2";
preset.DisplayName = "Ring of Gods";
preset.itemtex = LoadItemTex (preset.itemname);
preset.worldObject = LoadItemPrefab (preset.itemname);
inv.AddNewItem(preset, preset.itemname); //Here it's assumed that is added a new value to the Dictionaru when that Script loads (that script is before than "GameGUI" that request that code.
}
}
//Item Class
public class InventoryItem
{
public GameObject worldObject;
public int id;
public string itemname;
public string DisplayName;
public Texture itemtex;
public string itemtype;
public string equipmenttype;
public string usable;
public float itemweight;
public bool droppable;
public Transform itemmodel;
public int itemstacksize;
public int itemstacklimit;
public bool showStack;
public int bagsize;
public bool showBag;
public InventoryItem[] BagItem;
}
public class Inventory {
private Dictionary<string, InventoryItem> itemsBase = new Dictionary<string, InventoryItem>();
public void AddNewItem(InventoryItem item, string name) {
itemsBase.Add (name, item);
}
public InventoryItem FindItem(string name) {
return itemsBase[name];
}
}
public class GameGUI : MonoBehaviour {
public void Start() {
InventoryItem[] InventorySlots = new InventoryItem[5];
InventorySlots[3] = FindItem("Ring2"); //There is now the error: "The given key was not present in the dictionary."
}
}
Function “Find” gives me a that error, and I don’t know what can I do… Where is my error?
Can somebody checks my code?
Thanks in advance.
Bye.