Files
Gen_Hack-and-Slash-Roguelite/Client/Assets/Scripts/Entity/InventorySlot.cs

78 lines
2.5 KiB
C#

using UnityEngine;
namespace Entity
{
/// <summary>
/// 表示背包中的一个槽位,存储特定类型的物品及其数量。
/// </summary>
public class InventorySlot
{
public Item.ItemResource Item { get; private set; } // 槽位中的物品资源
public int Quantity { get; private set; } // 槽位中物品的数量
/// <summary>
/// 创建一个新的背包槽位。
/// </summary>
/// <param name="item">槽位中的物品资源。</param>
/// <param name="quantity">初始数量。</param>
public InventorySlot(Item.ItemResource item, int quantity)
{
if (item == null)
{
Debug.LogError("InventorySlot cannot be initialized with a null ItemResource.");
return;
}
Item = item;
Quantity = Mathf.Max(0, quantity); // 确保数量不为负
// 确保初始数量不超过最大堆叠
if (Quantity > Item.MaxStack)
{
Debug.LogWarning(
$"Initial quantity {Quantity} for {Item.Name} exceeds MaxStack {Item.MaxStack}. Clamping to MaxStack.");
Quantity = Item.MaxStack;
}
}
/// <summary>
/// 向槽位中添加指定数量的物品。
/// </summary>
/// <param name="amount">要添加的数量。</param>
/// <returns>实际添加的数量。</returns>
public int AddQuantity(int amount)
{
if (Item == null || amount <= 0) return 0;
var spaceLeft = Item.MaxStack - Quantity;
if (spaceLeft <= 0) return 0; // 槽位已满
var added = Mathf.Min(amount, spaceLeft);
Quantity += added;
return added;
}
/// <summary>
/// 从槽位中移除指定数量的物品。
/// </summary>
/// <param name="amount">要移除的数量。</param>
/// <returns>实际移除的数量。</returns>
public int RemoveQuantity(int amount)
{
if (Item == null || amount <= 0) return 0;
var removed = Mathf.Min(amount, Quantity);
Quantity -= removed;
return removed;
}
/// <summary>
/// 获取槽位是否为空。
/// </summary>
public bool IsEmpty => Quantity <= 0;
/// <summary>
/// 获取槽位是否已满。
/// </summary>
public bool IsFull => Item != null && Quantity >= Item.MaxStack;
}
}