Unity3d character replacement Mesh merging (material merging) and unity3dmesh
In the previous tutorial
Unity3d substitution for Model Animation Separation
This section describes how to combine the animation of the body parts of a character to make the model move. However, in UnityEditor, we can see that the four parts of the Model exist independently in the form of four gameobjects, we can guess the impact of this. When playing a character animation, for example, to let the character model move around, we need to call
head.animation.Play("run"); jack.animation.Play("run"); pant.animation.Play("run"); weapon.animation.Play("run");
Only when the same action is performed on the four parts can the entire person be moved. This undoubtedly adds a lot of operations, which is confusing.
How can this problem be solved?
The Model Animation merging function is provided in Unity. That is to say, we can merge the four parts of the character model into a GameObject, in this way, we only need a sentence of code to perform operations on the characters.
The following uses a simple Demo as an example.
Construct the following scenario:
Three cubes under Character are labeled with textures of different colors for easy identification and experimentation.
Merge the Mesh and material to the Character GameObject.
Using UnityEngine; using System. collections; public class NewBehaviourScript: MonoBehaviour {// Use this for initializationvoid Start () {// get MeshRender; MeshRenderer [] meshRenders = GetComponentsInChildren <MeshRenderer> (); // material; material [] mats = new Material [meshRenders. length]; for (int I = 0; I <meshRenders. length; I ++) {mats [I] = meshRenders [I]. sharedMaterial;} // merge Mesh; MeshFilter [] meshFilters = GetComponentsInChildren <MeshFilter> (); CombineInstance [] combine = new CombineInstance [meshFilters. length]; for (int I = 0; I <meshFilters. length; I ++) {combine [I]. mesh = meshFilters [I]. sharedMesh; combine [I]. transform = meshFilters [I]. transform. localToWorldMatrix; meshFilters [I]. gameObject. setActive (false);} transform. gameObject. addComponent <MeshRenderer> (); transform. gameObject. addComponent <MeshFilter> (); transform. getComponent <MeshFilter> (). mesh = new Mesh (); transform. getComponent <MeshFilter> (). mesh. combineMeshes (combine, false); transform. gameObject. setActive (true); transform. getComponent <MeshRenderer> (). sharedMaterials = mats;} // Update is called once per framevoid Update (){}}
Mount the script above to Character.
Effect after running:
Download the project example;
http://pan.baidu.com/s/1o6socoM