在 Unity 3d 中排序列表内存不足?

Sorted list out of memory in Unity 3d?

编辑器提示错误:内存不足。大家好,我正在学习排序列表。 PrintMessage 方法每秒运行一次。添加功能导致了错误。你能根据代码 blow 判断出什么问题吗?谢谢。

void PrintMessage(GameObject gameObject) {
    Target newTarget = new Target(gameObject, transform.position);
    targets.Add(newTarget);
    print(targets[targets.Count-1].Distance.ToString());
}

public void Add(T item)
{
    int num;
    // add your implementation below
    if (items.Count != 0)
    {
        for (int i = 0; i < items.Count; i++)
        {
            num = item.CompareTo(items[i]);
            if (num >= 0)
            {
                tempList.AddRange(items.GetRange(i, items.Count - i));
                items.RemoveRange(i, items.Count - i);
                items.Add(item);
                items.AddRange(tempList);
                tempList.Clear();
                continue;
            }
        }
        items.Add(item);
    }
    else
    {
        items.Add(item);
    }
}

问题是

里面
for (int i = 0; i < items.Count; i++)
{
    ...
    items.Add(item);
    ...
}

您不断添加越来越多的项目。因此,循环的每次迭代 items.Count 都会大 +1 item => 永远不会满足退出条件 i >= items.Count

永不 在遍历同一列表时更改列表计数!

最后的原因是您正在使用 continue(转到下一次迭代).. 这没有任何意义,因为此时下一次迭代将开始。

你可能会提到 break(中断循环)甚至 return 因为无论如何在循环之后你再次调用 items.Add(item) ...


您可能更想使用 List<T>.Insert(int index, T item)

public void Add(T item)
{
    int newIndex = 0;

    // You don't need an additional if-else
    // since this loop is anyway never executed
    // if (items.Count == 0)
    for (int i = 0; i < items.Count; i++)
    {
        num = item.CompareTo(items[i]);
        if (num >= 0)
        {
            // we want to add the new item AFTER
            // the item we compared it to
            newIndex = i+1;
            return;
        }
    }

    // Inserts the item at index newIndex
    // if newIndex == items.Count this equals Add
    items.Insert(newIndex, item);
}

请注意,这实际上已经存在!

叫做SortedSet<T>