Skinned Mesh how to connect bones to mesh help

Hi everyone!

I want to bind my mesh with script code to a bone animation! Most of the parts I understand, but I have trouble to find the connection between bones and mesh!

Hope someone can tell me, what I’m missing, or explain it to me. bones and BoneWeight seems logical not connected, but that can’t be? Thx!

    gameObject.AddComponent<Animation>();
	SkinnedMeshRenderer renderer = gameObject.AddComponent<SkinnedMeshRenderer>();
	
	
	/*MESH*/
	Mesh sourceMesh = Instantiate(baseMesh) as Mesh;
	sourceMesh.RecalculateNormals();
	
	BoneWeight[] weights = new BoneWeight[sourceMesh.vertexCount];
	for(int i = 0; i < weights.Length; i++){
		weights*.boneIndex0 = 0;*

_ weights*.weight0 = 1;_
_
}_
_
sourceMesh.boneWeights = weights;*_

_ /SKELETON/_
* Transform[] bones;*
* Transform sourceSkeleton = Instantiate(skeleton) as Transform;*

* sourceSkeleton.name = “skeleton”;*
* sourceSkeleton.parent = gameObject.transform;*

* bones = gameObject.GetComponentsInChildren();*

_ /BIND POSES/
* Matrix4x4[] bindPoses = new Matrix4x4[bones.Length];*
* for(int i = 0; i < bindPoses.Length; i++){*
bindPoses = bones.worldToLocalMatrix * transform.localToWorldMatrix;
* }*_

_ /MATERIAL/
* Material materials = new Material[3];
materials[0] = materials[1] = materials[2] = new Material(Shader.Find(" Diffuse"));
renderer.materials = materials;*_

_ /END/
* sourceMesh.bindposes = bindPoses;
renderer.bones = bones;
renderer.sharedMesh = sourceMesh;*_

BoneWeight.boneIndex0, 1, 2, 3 hold an index into the bones array to specify which bone(s) should be used by this vertex. BoneWeight.weight0, 1, 2, 3 is the corresponding weight for the bone. Note that the weights are normalized by Unity. So if you use 4 bones and you set all weights to 0.1 all 4 will be 0.25.

Finally the boneweights belong to the Mesh but the bones itself (the Transform array) belongs to the SkinnedMeshRenderer. When the skinnedMeshRenderer renders the Mesh it uses the boneweights of the mesh together with the bones array to skin the Mesh.

To conclude:

Each vertex have it’s boneweigth. The boneweight’s boneindex references a generic bones array which belongs to the Renderer.

The actual connection between them is this line:

renderer.sharedMesh = sourceMesh;

which tells the renderer to use this mesh.