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.
// Use this for initialization
void Start ()
{
vertices = mesh.vertices;
int n = mesh.vertexCount;
Debug.Log ("vertex count" + n);
//Bone Weights
weights=new BoneWeight[mesh.vertexCount];
weights = mesh.boneWeights;
Debug.Log ("vertex 2:" + weights [2].weight2 + "vertex 100:" + weights [100].weight0);
//Renderer
top = this.transform.Find("Tops").gameObject;
SkinnedMeshRenderer meshRend = top.GetComponent<SkinnedMeshRenderer> ();
//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 setting
tshirt.AddComponent<Animator>();
tshirt.GetComponent<Animator> ().avatar = humanAvatar;
tshirt.GetComponent<Animator> ().applyRootMotion = true;
tshirt = tshirt.transform.Find ("Tops").gameObject;
//blendMeshRend = tshirt.AddComponent<SkinnedMeshRenderer> ();
blendMeshRend = tshirt.GetComponent<SkinnedMeshRenderer> ();
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;
}