UnityException: Transform child out of bounds

Hello guys :slight_smile:

Someone could help me fidn out where is the problem of UnityException: Transform child out of bounds? Code:

 bone = new Transform[gameObject.transform.childCount];
            bindPoses = new Matrix4x4[mesh.vertexCount];
            boneWeights = new BoneWeight[mesh.vertexCount];
            Vector3[] vertices = mesh.vertices;
            Debug.Log("Bones: " + bone.Length + "BindBones: " + bindPoses.Length + " Weights: " + boneWeights.Length

            for (int index = 0; index <= mesh.vertexCount; index++)
                if(this.gameObject.transform.childCount > 0) { 
                bone[index] = this.gameObject.transform.GetChild(index); < ----"UnityException: Transform child out of bounds"----->
                bone[index].transform.position = this.transform.TransformPoint(mesh.vertices[index]);

                bindPoses[index] = bone[index].transform.worldToLocalMatrix * this.transform.localToWorldMatrix;
                boneWeights[index].boneIndex0 = index;
                boneWeights[index].weight0 = 1;

Thanks for your time :slight_smile:

Hi there,

You are looping from 0 to the number of vertex in your mesh. It seems that your gameObject has got a different (less) number of children than vertexCount value.

Are you sure that your gameObject has as many children as number of vertex has the mesh?

If you want to make it work as it is… You have to change the condition in the “if” statement:

if(this.gameObject.transform.childCount > index)

That way, you are avoiding the Exception, as you won’t access a non-existing children.

Hope it helps.

It means you are trying to retrieve a child with a higher index than is available. As the index is incremented towards the mesh.vertexCount, make sure that the vertexCount isn’t higher than the amount of children. You could place a check before the for loop so you know it will enter the for loop with the right data. Lets say childCount == 3, then childs(0) , (1) and (2) can be retrieved. Because of the [less or equal to sign] mesh.vertexCount in the for loop, the vertexCount can’t be higher then 2. (I couldn’t get the sign to display normally :P)