The relevant portion of the code is here:
int i;
Transform rootParent = transform.root.transform;
GameObject target;
Transform[] bodyBones = null;
for (i = 0; i < rootParent.GetChildCount (); i++)
{
target = rootParent.GetChild (i).gameObject;
if (target.GetComponent<SkinnedMeshRenderer> () != null)
{
bodyBones = target.GetComponent<SkinnedMeshRenderer> ().bones;
break;
}
}
This says it's expecting your transform hierarchy to look something like this:
- Character root object (this should not be parented under any other scene object)
- Some number of child objects (sound emitters, colliders, etc)
- Character visual (the GameObject with the
SkinnedMeshRenderer
component) - Maybe more child objects
- Maybe some grand children
- Clothing object (the one running the
AttachToBody
script)
- Clothing object (the one running the
- Maybe some grand children
ie. The character's skinned mesh must be a direct child of the clothing object's most distant ancestor.
Myself, I'd usually use a different style, replacing the above code with the following:
Transform[] bodyBones = null;
var skinnedMesh = transform.parent.GetComponentInChildren<SkinnedMeshRenderer();
if(skinnedMesh != null)
bodyBones = skinnedMesh.bones;
With this, your clothing item can be:
- a direct child of the Skinned Mesh
- a sibling of the Skinned Mesh under a common direct parent
- an aunt / great aunt of the Skinned Mesh, where the direct parent of the clothing item is a grandparent or great grandparent of the Skinned Mesh
Using the clothing item's direct parent rather than its root gives you more flexibility if you want to use empty GameObjects as folders to organize your scene, or bundle together content that needs to be enabled/disabled/moved/searched as a group.