Search Unity

Error separating children from parent

Discussion in 'Scripting' started by Lesnikus5, Mar 28, 2020.

  1. Lesnikus5

    Lesnikus5

    Joined:
    May 20, 2016
    Posts:
    131
    I can not understand why the error occurs.

    I am trying to separate all children from a parent, but an error appears:

    UnityException: Transform child out of bounds.

    The Scripting API says that:
    "If the transform has no child, or the index argument has a value greater than the number of children then an error will be generated. In this case" Transform child out of bounds "error will be given"

    But i used transform.childCount and going beyond should not occur. I have 240 children, when the process reaches 119, this error occurs. Some of the children are separated, some remain in the parent. The process just stops in the middle.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Test1 : MonoBehaviour {
    6.  
    7.     public Transform parentTrans;
    8.  
    9.     void Start ()
    10.     {
    11.         int childsCount = parentTrans.childCount;
    12.         Debug.Log(childsCount);
    13.    
    14.         for (int i = 0; i < childsCount; i++)
    15.         {
    16.             Transform child = parentTrans.GetChild(i);
    17.             child.parent = null;
    18.             Debug.Log(i);
    19.         }
    20.         Destroy(parentTrans.gameObject);
    21.     }
    22. }
    23.  
     
    Last edited: Mar 28, 2020
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,187
    The problem is you are looping through the children and removing them from the front instead of the back. Think of it this way. You have 10 children, so your count is 10. You remove the first child, which shifts everything. So the child in index 9 is now in index 8, but your for loop still tries to go to index 9. Children is just a collection under it's parent, so it behaves just like a list.

    Just change your for loop

    Code (CSharp):
    1. for(int i = childsCount-1;i>= 0;i--)
    Which will start you at the last child and work your way back.
     
    Lesnikus5 likes this.
  3. Lesnikus5

    Lesnikus5

    Joined:
    May 20, 2016
    Posts:
    131
    Thank you.