我使用视频教程在Unity中制作游戏,编写了与该教程相同的代码,但是在视频教程中,所有内容都有效,并且代码中有错误。 我正在尝试制作可堆叠的库存:
public void AddItem(int id)
{
Item itemToAdd = database.FetchItemByID(id);
if (itemToAdd.Stackable && CheckIfItemIsInInventory(itemToAdd))
{
for (int i = 0; i < items.Count; i++)
{
if (items[i].ID == id)
{
ItemData data = slots[i].transform.GetChild(0).GetComponent<ItemData>();
data.amount++;
data.transform.GetChild(0).GetComponent<Text>().text = data.amount.ToString();
break;
}
}
}
else {
for (int i = 0; i < items.Count; i++)
{
if (items[i].ID == -1)
{
items[i] = itemToAdd;
GameObject itemObj = Instantiate(inventoryItem);
itemObj.transform.SetParent(slots[i].transform);
itemObj.transform.position = Vector2.zero;
itemObj.GetComponent<Image>().sprite = itemToAdd.Sprite;
itemObj.name = itemToAdd.Title;
break;
}
}
}
}
当您尝试使用AddItem(id)创建可堆叠对象时;我收到以下错误:
KeyNotFoundException: The given key was not present in the dictionary.
System.Collections.Generic.Dictionary`2[System.String,LitJson.JsonData].get_Item (System.String key) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:150)
LitJson.JsonData.get_Item (System.String prop_name)
ItemDatabase.ConstructItemDatabase () (at Assets/Scripts/ItemDatabase.cs:33)
ItemDatabase.Start () (at Assets/Scripts/ItemDatabase.cs:16)
和
NullReferenceException: Object reference not set to an instance of an object
Inventory.AddItem (Int32 id) (at Assets/Scripts/Inventory.cs:39)
Inventory.Start () (at Assets/Scripts/Inventory.cs:32)
我犯了什么错误?