transform.SetParent seems to be causing problems

I have an object pool set up. Its items, when in use, are parented to another object (for gameplay purposes). After the object is done with an item it is parented back to the pool object and deactivated, ready for future use.

This is the code that clears the object of it’s children (which come from the object pool)
‘op’ is the object pool component by the way.

public void ClearModels()
{
    for (int i=0; i<transform.childCount; i+=1)
    {
        op.Push(transform.GetChild(i).gameObject);
    }
}

This is the object pool’s ‘Push’ function, which should parent it back the its gameObject and deactivate it.

public void Push(GameObject obj)
{
    if (obj.name == template.name)
    {
        obj.SetActive(false);
        obj.transform.SetParent(folder.transform);
        items.Add(obj);
    }
}

Now, for whatever reason, when the function ‘ClearModels’ is run it will only return some of the child objects back into the object pool. However, when I remove ‘obj.transform.SetParent(folder.transform);’ it returns all of them back to the object pool. Any idea why that is?

You are removing children from their parent while iterating over them. So after removing child 0, i is 1 but childCount has decreased by 1.
Please iterate from childCount-1 to 0 instead, or store the references to all children before using setParent on them.

1 Like

Oh wow, now I feel dumb, that was the problem. Thank you! :slight_smile: