- Home /
Binding a mecanim skeleton to a new mesh
Hi,
I am trying to add the skeleton to a new mesh in my scene. The original mesh contains the skeleton and the model moves according to the bone position and rotation. I now have a new mesh without a skeleton. I want to skin this new mesh to this existing skeleton. Below is my code where I copy the bone weights and add the skinned mesh renderer.
It doesn't work. It deforms my new mesh terribly. Just for background, my new mesh is just an x-scaled version of the old mesh without the skeleton attached.
void Start ()
{
vertices = mesh.vertices;
//Get original mesh bone weights
weights=new BoneWeight[mesh.vertexCount];
weights = mesh.boneWeights;
// Get original mesh Renderer
top = this.transform.Find("Tops").gameObject;
SkinnedMeshRenderer meshRend = top.GetComponent<SkinnedMeshRenderer> ();
//Get original mesh Skeleton
Transform[] originalMeshBones;
originalMeshBones = meshRend.bones;
Matrix4x4[] bindPoses = mesh.bindposes;
for(int i = 0; i < 16; i++){
bindPoses[i] = originalMeshBones[i].worldToLocalMatrix * transform.localToWorldMatrix;
}
//Blend Mesh settings; tshirt is the blend mesh game object
tshirt.AddComponent<Animator>();
tshirt.GetComponent<Animator> ().avatar = humanAvatar;//human avatar is the original mesh avatar
tshirt.GetComponent<Animator> ().applyRootMotion = true;
tshirt = tshirt.transform.Find ("Tops").gameObject;
//add skinned mesh renderer component to the new(blend) mesh
blendMeshRend = tshirt.AddComponent<SkinnedMeshRenderer> ();
//copy the bone weights and bind poses and bones
BoneWeight[] blendMeshWeights=new BoneWeight[mesh.vertexCount];
blendMesh.boneWeights = weights;
Debug.Log ("vertex 2: " + blendMesh.boneWeights [2].weight2 + "vertex 100:" + blendMesh.boneWeights [100].weight0);
blendMesh.bindposes = bindPoses;
Debug.Log ("bind poses 0"+blendMesh.bindposes [7].m00);
blendMeshRend.bones = originalMeshBones;
//tshirt.transform.parent = this.transform;
blendMeshRend.sharedMesh = blendMesh;
blendMeshRend.rootBone = meshRend.rootBone;
}
Both rigs need to have to same hierarchy and number of bones.
http://answers.unity3d.com/questions/44355/shared-skeleton-and-animation-state.html
I have just one rig: the main skeleton. I need to bind a mesh (which is not skinned currently) to this skeleton.
Answer by xXx12aithexXx · Jun 10, 2016 at 03:18 PM
why not just bind the bones from a 3D editor ? and switch out the mesh .... I like were you're going with this so I'm guessing there is a reason to make it more complex?
Hi, Thanks for your comment. I need to change the bone positions of the skeleton in my script at run time. Since I update the skeleton in script, I cannot bind it in a 3D editor before. Now, if I change the joint positions with the new mesh attached, it will further deform the mesh. This is what I want to:
Update the bone positions of the skeleton.
Bind the new mesh (which correctly matches the new bone positions) to this skeleton