You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity实现支持堆叠的背包物品存入功能 用嵌套循环替代多列表方案

实现方案

1. 补充必要字段

你的UISlot类缺少堆叠数量存储字段,先做修改:

public class UISlot : MonoBehaviour
{
    public FoodResource item;
    public Image slotImage;
    public Sprite icon;
    public Text itemCount;
    public int stackCount; // 新增:存储当前格子的物品堆叠数量
}

2. 嵌套循环实现背包堆叠逻辑

核心逻辑分两轮:优先把物品堆叠到已有同类型的格子里,剩余物品再占用新空格子,实现代码如下:

public void AddToInventory(List<FoodResource> food)
{
    // 复制待添加物品列表,避免修改原传入数据
    List<FoodResource> remainingFood = new List<FoodResource>(food);

    // 第一轮:堆叠到已有同类型格子
    for (int s = 0; s < slots.Length; s++)
    {
        if (slots[s].item == null) continue;
        // 倒序遍历避免移除元素时索引错乱
        for (int f = remainingFood.Count - 1; f >= 0; f--)
        {
            // 可自行更换判断条件,比如用foodType枚举对比效率更高
            if (remainingFood[f].uniqueName == slots[s].item.uniqueName)
            {
                slots[s].stackCount++;
                slots[s].itemCount.text = slots[s].stackCount.ToString();
                remainingFood.RemoveAt(f);
            }
        }
    }

    // 第二轮:剩余物品放空格子
    for (int s = 0; s < slots.Length; s++)
    {
        if (remainingFood.Count == 0) break;
        if (slots[s].item != null) continue;

        // 取首个剩余物品初始化空格子
        FoodResource currentItem = remainingFood[0];
        slots[s].item = currentItem;
        slots[s].icon = currentItem.sprite;
        slots[s].slotImage.sprite = currentItem.sprite;
        slots[s].slotImage.enabled = true;
        slots[s].stackCount = 1;
        remainingFood.RemoveAt(0);

        // 同类型剩余物品直接堆叠到当前格子
        for (int f = remainingFood.Count - 1; f >= 0; f--)
        {
            if (remainingFood[f].uniqueName == currentItem.uniqueName)
            {
                slots[s].stackCount++;
                remainingFood.RemoveAt(f);
            }
        }
        slots[s].itemCount.text = slots[s].stackCount.ToString();
    }

    // 可选逻辑:如果remainingFood.Count>0说明背包已满,自行添加提示
}

补充说明

  • 如果要设置单格堆叠上限,只需要在堆叠逻辑前加slots[s].stackCount < 上限值的判断即可,超出上限的物品会自动分配到下一个空格子
  • 物品匹配规则可根据业务需求调整,用foodType枚举判断比字符串对比性能更好

内容的提问来源于stack exchange,提问作者Marty Carr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 06:27:02