using UnityEngine; namespace Entity { /// /// 表示背包中的一个槽位,存储特定类型的物品及其数量。 /// public class InventorySlot { public Item.ItemResource Item { get; private set; } // 槽位中的物品资源 public int Quantity { get; private set; } // 槽位中物品的数量 /// /// 创建一个新的背包槽位。 /// /// 槽位中的物品资源。 /// 初始数量。 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; } } /// /// 向槽位中添加指定数量的物品。 /// /// 要添加的数量。 /// 实际添加的数量。 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; } /// /// 从槽位中移除指定数量的物品。 /// /// 要移除的数量。 /// 实际移除的数量。 public int RemoveQuantity(int amount) { if (Item == null || amount <= 0) return 0; var removed = Mathf.Min(amount, Quantity); Quantity -= removed; return removed; } /// /// 获取槽位是否为空。 /// public bool IsEmpty => Quantity <= 0; /// /// 获取槽位是否已满。 /// public bool IsFull => Item != null && Quantity >= Item.MaxStack; } }