【问题标题】:Sorted list out of memory in Unity 3d?Unity 3d中的排序列表内存不足?
【发布时间】:2019-04-04 13:36:48
【问题描述】:

编辑说错误:内存不足。大家好,我正在学习排序列表。 PrintMessage 方法每秒运行一次。并且 Add 功能导致了该错误。您能根据代码打击判断出什么问题吗?谢谢。

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);
    }
}

【问题讨论】:

  • 为什么还需要targets.Add(newTarget)?该方法用于“打印对象”,因此不需要将对象添加到列表中。
  • 无论如何它都会将一个新的目标对象添加到排序列表中。最后将打印最近的物距。
  • 您正在遍历所有项目,并将每个项目添加到循环中的“项目”中。因此,您的增长是指数级的。你确定你想要那个内部的items.Add(item) 电话吗? (在 for 循环内)?
  • 而不是continue;,你可能想做return; .. 否则你在for 循环中调用items.Add 至少两次甚至更频繁......
  • 我明白了。多谢你们。回报是我想做的。我认为 continue 也可以。

标签: list unity3d out-of-memory sortedlist


【解决方案1】:

问题是在里面

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

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

&rightarrow; 永远不要在迭代同一个列表时更改列表计数!

最终的原因是您使用的是continue(进行下一次迭代) .. 这没有任何意义,因为此时无论如何下一次迭代都会开始。

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


您可能更愿意使用List&lt;T&gt;.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&lt;T&gt;

【讨论】:

  • 我之前使用过 items.Insert,但 Insert 也在 for 循环中,哈哈。感谢您的回复和新的解决方案。它让我爱上了这个网站!多么可爱的人在这里闲逛。问题解决得这么快!!!
  • 查看我的最新更新 .. 你结帐了吗SortedSet&lt;T&gt; .. 它基本上正是你想要实现的 ;)
  • 当然我会检查的。再次感谢你!! :)
猜你喜欢
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
  • 2016-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
  • 1970-01-01
相关资源
最近更新 更多