JinChanChan/Assets/Scripts/BeiBao/InventorySlot.cs

50 lines
1.2 KiB
C#

namespace BeiBao
{
/// <summary>
/// 背包格子类
/// 每个背包格子存储一种物品,并管理物品数量和堆叠。
/// </summary>
public class InventorySlot
{
private Item _item;
/// <summary>
/// 物品
/// </summary>
public Item Item => _item;
public bool IsEmpty => Item == null;
// 将物品添加到格子中
public bool AddItem(Item item, int quantity)
{
if (IsEmpty)
{
_item = item;
return Item.AddQuantity(quantity) == 0;
}
if (Item.ItemID == item.ItemID && Item.Quantity < Item.MaxStack)
{
int remaining = Item.AddQuantity(quantity);
return remaining == 0;
}
return false;
}
// 从格子中取出物品
public bool RemoveItem(int quantity)
{
if (Item != null && Item.RemoveQuantity(quantity))
{
if (Item.Quantity == 0)
{
_item = null; // 如果物品数量为零,则清空格子
}
return true;
}
return false;
}
}
}