【发布时间】:2020-09-10 15:58:56
【问题描述】:
我已经准备好了所有东西,但是我在将库存中创建的项目设置为实际插槽时遇到了问题。我这样做是为了更好地了解这些项目。
这是库存代码:
// Amount of Slots in inventory defined here!!!
[SerializeField]
private Slot[] slots = new Slot[10];
public List<Item> invItems = new List<Item>();
public void CheckSlot(Item item)
{
for (int i = 0; i < slots.Length; i++)
{
if (slots[i].isEmpty == false)
{
//call a method.
if (item.isStackable)
{
slots[i].amount = item.amount;
}
}
if (slots[i].isEmpty == true)
{
//call another method.
//run some code.
slots[i] = new Slot(item);
return;
}
}
}
public void UpdateAmount(Item _item,Slot _slot)
{
_slot.amount = _item.amount;
}
public void CreateItem(Item item)
{
Item invItem1 = new Item();
invItem1 = item.Copy();
invItems.Add(invItem1);
}
public void InventoryAdd(Item item)
{
//check if the item is already in the inventory
//if true check if it is stackable and the new amount is less than maxStackable amount
//if false add the item to the invItems list and set the slot to false
if (invItems.Count != 0)
{
for (int i = 0; i < invItems.Count; i++)
{
if (invItems[i].ItemID == item.ItemID)
{
if (invItems[i].amount + item.amount <= invItems[i].maxStackable)
{
invItems[i].amount += item.amount;
CheckSlot(invItems[i]); //
return;
}
if (invItems[i].amount < invItems[i].maxStackable)
{
if (invItems[i].amount + item.amount > invItems[i].maxStackable)
{
int nextAmount = invItems[i].maxStackable - invItems[i].amount;
invItems[i].amount += nextAmount;
Item invItem1 = new Item();
invItem1 = item.Copy();
invItem1.amount = invItem1.amount - nextAmount;
invItems.Add(invItem1);
return;
}
}
}
}
}
Item invItem = new Item();
invItem = item.Copy();
invItems.Add(invItem);
和项目脚本:
public string name;
public int ItemID;
public GameObject prefab;
public Sprite icon;
public int amount = 1;
public bool isStackable;
public int maxStackable = 5;
public Item()
{
}
public Item(string _name, int id,GameObject _prefab, int _amount, bool stackable,int maxStack)
{
name = _name;
ItemID = id;
prefab = _prefab;
amount = _amount;
isStackable = stackable;
maxStackable = maxStack;
}
public Item Copy()
{
Item copy = new Item();
copy.name = this.name;
copy.ItemID = this.ItemID;
copy.prefab = this.prefab;
copy.amount = this.amount;
copy.isStackable = this.isStackable;
copy.maxStackable = this.maxStackable;
return copy;
}
以及插槽的代码:
public bool isEmpty = true;
public Slot()
{
}
public Slot(Item _item)
{
this.name = _item.name;
this.ItemID = _item.ItemID;
this.isStackable = _item.isStackable;
this.prefab = _item.prefab;
this.icon = _item.icon;
}
问题是我不知道如何将我在库存中创建的项目设置到插槽。也许我需要清理我的代码,并一次检查这些东西而不是单独检查?
【问题讨论】: