Search code examples
listunity-game-engineout-of-memorysortedlist

Sorted list out of memory in Unity 3d?


Editor is saying error: Out of memory. Hi guys, I am learning about the sorted list. The method PrintMessage runs every second. And the Add funtion is causing the bug. Would you be able to tell what's wrong based on the code blow? Thank you.

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

Solution

  • The problem is that inside of

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

    you continously add more and more items. So every iteration of the loop the items.Count will be +1 item bigger => the exit condition i >= items.Count will never be met.

    Never change the List count while iterating over the same list!

    Reason for that in the end is you're using continue(go to the next iteration) .. it makes no sense there since at this point anyway the next iteration would start.

    You probably ment break(interrupt the loop) or even return since anyway right after the loop again you call items.Add(item) ...


    You probably rather want to use 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);
    }
    

    Note that this actually already exists!

    It is called SortedSet<T>