Problem with adding object to array

Hi,

I have an object with 8 children objects. And I need a function that returns only 6 of them, matching by name.

The problem is, when I declare an array of length 6, unity errors out that my array is not big enough:

IndexOutOfRangeException: Index was outside the bounds of the array.

But when I set the length to 7 it works, but then I get 1 extra object null. This is my weird code:

GameObject[] GetDetailChildren(GameObject Act_CubeMesh) {
    GameObject Houdini_TransformNode = Act_CubeMesh.transform.GetChild(0).gameObject.transform.GetChild(0).gameObject;
    Transform TR = Houdini_TransformNode.transform;
    GameObject[] arr = new GameObject[6];
    for (int i=0; i<TR.childCount; i++) {
        GameObject child = TR.GetChild(i).gameObject;
        if (child.name == "detail_Xminus0" ||
            child.name == "detail_Xplus0" ||
            child.name == "detail_Yminus0" ||
            child.name == "detail_Yplus0" ||
            child.name == "detail_Zminus0" ||
            child.name == "detail_Zplus0") {
            arr *= child;*

}
}
return arr;
}

because you have more childs that array length, you are trying to set one object at the position7 of the array when there is no position 7. you can just create a second var

int j = 0;

and only increase j by one inside the if

    if (child.name == "detail_Xminus0" ||
         child.name == "detail_Xplus0" ||
         child.name == "detail_Yminus0" ||
         child.name == "detail_Yplus0" ||
         child.name == "detail_Zminus0" ||
         child.name == "detail_Zplus0") {
         arr[j] = child;
         j++;
     }

The problem is your code is lets say your “detail_Zplus0” is your 7th object you are trying to do this: arr[7] = child which causes the problem. Instead you can use a list like this:

List<GameObject> GetDetailChildren(GameObject Act_CubeMesh)
    {
        GameObject Houdini_TransformNode = Act_CubeMesh.transform.GetChild(0).gameObject.transform.GetChild(0).gameObject;
        Transform TR = Houdini_TransformNode.transform;
        List<GameObject> arr = new List<GameObject>();
        for (int i = 0; i < TR.childCount; i++)
        {
            GameObject child = TR.GetChild(i).gameObject;
            if (child.name == "detail_Xminus0" ||
                child.name == "detail_Xplus0" ||
                child.name == "detail_Yminus0" ||
                child.name == "detail_Yplus0" ||
                child.name == "detail_Zminus0" ||
                child.name == "detail_Zplus0")
            {
                arr.Add(child);
            }
        }
        return arr;
    }

Now you do not have to deal with size.