Hi,
I’ve encountered an awkwar error and I’m wondering what may cause it: let’s say I have a GameObject with three children, named child1, child2 and child3.
-parentObject
–child1
–child2
–child3
I checkGameObject.transform.childCount, then do:
for(int i = 0; i < transform.childCount; i++)
{
Debug.Log(tranform.GetChild(i).name;
}
One would expect that console will print sth like: child1, child2, child3. Meanwhile, it prints child1, child3, child3. Why is that? Is it some Unity error, or sometinhg obvious I cannot see myself?
As a side note, these objects are result of Network.Instantiate.
First check that the objects that you are instantiating are correct in the Hierarchy.
Now, GetChild has always been unreliable.
On mobile the child list is even ordered differently than what you see in the Editor.
So if you have 2 children and the first one is a rigidbody,
using gameObject.transform.GetChild(0).gameObject.GetComponent().enabled = false;
For example might return a null reference exception as the order of the children might change and GetChild(0) would return the other gameObject (that doesn’t have a rigidbody).
I would suggest using FindChild(“ChildName”).
It’s more accurate, never misses and is as fast.
As for your example, to get away from GetChild, i would use a foreach:
foreach(Transform child in this.transform){
Debug.Log(child.gameObject.name);
}