Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

transform.SetParent seems to be causing problems

Discussion in 'Scripting' started by Afropenguinn, Sep 27, 2015.

  1. Afropenguinn

    Afropenguinn

    Joined:
    May 15, 2013
    Posts:
    305
    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.
    Code (CSharp):
    1. public void ClearModels()
    2. {
    3.     for (int i=0; i<transform.childCount; i+=1)
    4.     {
    5.         op.Push(transform.GetChild(i).gameObject);
    6.     }
    7. }
    This is the object pool's 'Push' function, which should parent it back the its gameObject and deactivate it.
    Code (CSharp):
    1. public void Push(GameObject obj)
    2. {
    3.     if (obj.name == template.name)
    4.     {
    5.         obj.SetActive(false);
    6.         obj.transform.SetParent(folder.transform);
    7.         items.Add(obj);
    8.     }
    9. }
    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?
     
  2. Mistale

    Mistale

    Joined:
    Apr 18, 2012
    Posts:
    173
    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.
     
    LMan likes this.
  3. Afropenguinn

    Afropenguinn

    Joined:
    May 15, 2013
    Posts:
    305
    Oh wow, now I feel dumb, that was the problem. Thank you! :)