- Home /
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[i] = child;
}
}
return arr;
}
Answer by xxmariofer · Mar 12, 2019 at 11:55 AM
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++;
}
Answer by alikanat · Mar 12, 2019 at 11:59 AM
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.
Oh this is nice too.
Are there any advantages to use lists ins$$anonymous$$d of arrays?
array a bit better performance if you are not going to be changing the array elements much. list if you are going to be adding removing is better and easier to use (they can be resized)
Your answer
