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

C#移除元素时如何保持List大小不变?Unity库存场景适配

解决方案

要保持items列表的大小不变,你只需要把移除元素的操作改成将对应位置设为null,而不是调用List.Remove()方法(这个方法会直接删除元素并收缩列表)。同时还要修正RemoveItem和AddItem里的逻辑,确保槽位和列表的对应关系正确。

修改后的完整代码片段:

public class Inventory : MonoBehaviour
{
    public List<GameObject> items;

    public GameObject selectedGameObject;

    public int SelectedItem = 0;
    public int maxSlots;
    public int maxStack;

    public ItemSlot[] itemSlot;

    void Awake()
    {
        // 初始化列表,提前填充null到maxSlots的长度,确保初始大小固定
        items = new List<GameObject>(new GameObject[maxSlots]);
    }

    public void AddItem(string itemName, int quantity, Sprite itemSprite, string ItemDesc, GameObject itemObj)
    {
        // 找到第一个空的槽位(对应items里的null位置)
        for (int i = 0; i < maxSlots; i++)
        {
            if (items[i] == null)
            {
                itemSlot[i].AddItem(itemName, quantity, itemSprite, ItemDesc);
                items[i] = itemObj;
                selectedGameObject = itemObj;
                UpdateSelectedItem();
                return;
            }
        }

        // 如果所有槽位都满了,可以在这里加个提示
        Debug.Log("背包已满,无法添加物品");
    }
    
    public void RemoveItem(GameObject itemObj)
    {
        // 找到目标物品在items列表中的索引
        int targetIndex = items.IndexOf(itemObj);
        if (targetIndex == -1) return; // 没找到目标物品直接返回

        // 将列表对应位置设为null,保持列表长度不变
        items[targetIndex] = null;
        // 清空对应槽位的显示
        itemSlot[targetIndex].RemoveObj();

        // 如果当前选中的是被移除的物品,重置选中状态
        if (selectedGameObject == itemObj)
        {
            selectedGameObject = null;
            SelectedItem = -1;
        }
    }
}

关键修改点说明:

  • 初始化列表:在Awake里提前把items列表初始化为maxSlots长度的null数组,确保一开始列表大小就是固定值,不会随意变化。
  • AddItem逻辑调整:不再用items.Add(),而是遍历找第一个null的位置赋值,确保物品插入到空槽位,不会让列表长度超过maxSlots。
  • RemoveItem核心修改:用items.IndexOf(itemObj)找到目标索引,然后把items[targetIndex] = null,代替原来的items.Remove(itemObj),这样列表长度完全不变,只是把对应位置置空。
  • 槽位对应修正:原代码里遍历所有槽位调用RemoveObj是错误的,现在只处理目标索引对应的槽位,确保显示和列表数据一致。

这样修改后,不管移除多少物品,items列表的长度始终保持maxSlots,空的位置都是null,完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:02:29