using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(SkinnedMeshRenderer))] public class CombinePlayer : MonoBehaviour { public GameObject[] bodys; // Start is called before the first frame update void Start() { Replace(bodys,gameObject); } public void Replace(GameObject[] bodys, GameObject avatar) { Mesh mesh = new Mesh(); List<CombineInstance> combines = new List<CombineInstance>(); for (int i = 0; i < bodys.Length; i++) { CombineInstance combine = new CombineInstance(); combine.mesh = bodys[i].GetComponentInChildren<SkinnedMeshRenderer>().sharedMesh; combines.Add(combine); } mesh.CombineMeshes(combines.ToArray(), false, false); avatar.GetComponent<SkinnedMeshRenderer>().sharedMesh = mesh; List<Material> materials = new List<Material>(); for (int i = 0; i < bodys.Length; i++) { materials.Add(bodys[i].GetComponentInChildren<SkinnedMeshRenderer>().sharedMaterial); } avatar.GetComponent<SkinnedMeshRenderer>().materials = materials.ToArray(); Transform[] allbones = avatar.GetComponentsInChildren<Transform>(); Dictionary<string, Transform> dicbones = new Dictionary<string, Transform>(); foreach (var item in allbones) { dicbones.Add(item.name, item); } List<Transform> mybones = new List<Transform>(); for (int i = 0; i < bodys.Length; i++) { Transform[] bodybones = bodys[i].GetComponentInChildren<SkinnedMeshRenderer>().bones; for (int j = 0; j < bodybones.Length; j++) { if (dicbones.ContainsKey(bodybones[j].name)) { mybones.Add(dicbones[bodybones[j].name]); } } } avatar.GetComponent<SkinnedMeshRenderer>().bones = mybones.ToArray(); }
public void Huan(string[] id) { GameObject[] bodys = new GameObject[3]; bodys[0] = Resources.Load<GameObject>("Prefab/Tou_" + id[0]); bodys[1] = Resources.Load<GameObject>("Prefab/YiFu_" + id[1]); bodys[2] = Resources.Load<GameObject>("Prefab/Tui_" + id[2]); Transform[] allbones = gameObject.GetComponentsInChildren<Transform>(); Dictionary<string, Transform> dic_bone = new Dictionary<string, Transform>(); foreach (var item in allbones) { dic_bone.Add(item.name, item); } List<Transform> bones = new List<Transform>(); List<CombineInstance> combines = new List<CombineInstance>(); List<Material> materials = new List<Material>(); for (int i = 0; i < bodys.Length; i++) { SkinnedMeshRenderer sk = bodys[i].GetComponentInChildren<SkinnedMeshRenderer>(); CombineInstance combine = new CombineInstance(); combine.mesh = sk.sharedMesh; combines.Add(combine); materials.Add(sk.sharedMaterial); for (int j = 0; j < sk.bones.Length; j++) { if (dic_bone.ContainsKey(sk.bones[j].name)) { bones.Add(dic_bone[sk.bones[j].name]); } } } Mesh mesh = new Mesh(); mesh.CombineMeshes(combines.ToArray(), false, false); skinned.sharedMesh = mesh; skinned.materials = materials.ToArray(); skinned.bones = bones.ToArray(); }