【发布时间】:2020-10-26 07:39:56
【问题描述】:
我正在尝试实现一种可以调用来创建多个项目的方法
这是我试图让它工作的方法
public void AddMultipleItems(string[] itemKey, int[] amount)
{
for (int i = 0; i < itemKey.Length; i++)
{
Item item;
item = ItemCollection[itemKey[i]];
for (int x = 0; x < amount.Length; x++)
{
if (inventory.CanAddItem(item, amount[x]) == true)
{
inventory.AddItem(item.GetCopy());
}
else if (inventory.CanAddItem(item, amount[x]) == false)
{
Debug.Log("Inventory Full");
break;
}
}
}
}
然后会调用这个方法来添加这样的项目:
itemDB.AddMultipleItems(new string[] { "Boots", "Gold Coin", "Apple" }, new int[] {1, 2, 3 });
结果:我得到 3 个靴子、3 个金币和 3 个苹果。当我应该得到 1 个靴子、2 个金币和 3 个苹果时,
我也做过类似的方法,除了它不需要数组参数而且效果很好:
public void AddItems(string itemKey, int amount)
{
//First check if entered itemKey parameter exists in ItemCollection Dictionary
if (ItemCollection.ContainsKey(itemKey))
{
Item item;
item = ItemCollection[itemKey];
if (item != null)
{
//check if we can add the item and the amount of it
if (inventory.CanAddItem(item, amount))
{
//loop through the total amount
for (int i = 0; i < amount; i++)
{
//add the item
inventory.AddItem(item.GetCopy());
}
Debug.Log(itemKey + " Added Successfully!");
}
else
{
Debug.Log("Not enough space in Inventory");
}
}
else
{
Debug.Log("Null Item");
}
}
else
{
Debug.Log(itemKey + " does not exist in ItemDatabase's Dictionary");
}
}
所以基本上另一种看待它的方式是我如何将 AddItems(string itemKey, int amount) 变成 AddItems(string[] itemKey, int[] amount)强>。它的 for 循环、foreach 循环和数组有点让我绊倒,因为我不太擅长这些。
感谢任何帮助,谢谢!
【问题讨论】:
标签: arrays for-loop unity3d foreach inventory