//第一步是合并每个部件的网格
//第二步是合并材质球
//第三部是设置对应的骨头
//本脚本需挂载在对应avtar对象上,不然找不见对应骨头,无法实现效果
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CombinePlayer : MonoBehaviour
{
public GameObject[] bodys;
public int touId = 2;
public int tuiId = 1;
public int yifuId = 1;
// Start is called before the first frame update
private void Awake()
{
gameObject.AddComponent<SkinnedMeshRenderer>();
//调用换装方法
ChangeSkirt();
}
void Start()
{
}
public void ChangeSkirt()
{
//数组中添加对应的头 衣服 腿
//通过Resources加载
//模型生成图片看博客内的《通过unity3D模型转出图片》
bodys[0] = Resources.Load<GameObject>("Body/tou" + touId);
bodys[1] = Resources.Load<GameObject>("Body/tui" + tuiId);
bodys[2] = Resources.Load<GameObject>("Body/yifu" + yifuId);
//所有骨头集合
Transform[] allbones = GetComponentsInChildren<Transform>();
//骨头存入字典
Dictionary<string, Transform> dicbones = new Dictionary<string, Transform>();
//找到并添加所有骨头
for (int i = 0; i < allbones.Length; i++)
{
dicbones.Add(allbones[i].name, allbones[i]);
}
List<Transform> bonds = new List<Transform>();
//合并的实例集合
List<CombineInstance> combines = new List<CombineInstance>();
//合并材质的集合
List<Material> materials = new List<Material>();
for (int i = 0; i < bodys.Length; i++)
{
CombineInstance combine = new CombineInstance();
combine.mesh = bodys[i].GetComponentInChildren<SkinnedMeshRenderer>().sharedMesh;
combine.transform = bodys[i].transform.localToWorldMatrix;
combines.Add(combine);
materials.Add(bodys[i].GetComponentInChildren<SkinnedMeshRenderer>().sharedMaterial);
Transform[] bodybones = bodys[i].GetComponentInChildren<SkinnedMeshRenderer>().bones;
for (int j = 0; j < bodybones.Length; j++)
{
bonds.Add(dicbones[bodybones[j].name]);
}
}
Mesh mesh = new Mesh();
mesh.CombineMeshes(combines.ToArray());
GetComponent<SkinnedMeshRenderer>().sharedMesh = mesh;
GetComponent<SkinnedMeshRenderer>().materials = materials.ToArray();
GetComponent<SkinnedMeshRenderer>().bones = bonds.ToArray();
}
// Update is called once per frame
void Update()
{
}
}