/// <summary>
/// 网格合并
/// </summary>
/// <param name="tr"></param>
void CombineMesh(Transform tr)
{
MeshFilter[] meshFilters = tr.GetComponentsInChildren<MeshFilter>();//存储Meshfilters
MeshRenderer[] meshRenderers = tr.GetComponentsInChildren<MeshRenderer>();//存储meshRenderers
CombineInstance[] combineInstances = new CombineInstance[meshFilters.Length];//创建要存储网格的数组
Material[] materials = new Material[meshRenderers.Length];//创建要存储材质的数组
for (int i = 0; i < meshFilters.Length; i++)
{
combineInstances[i].mesh = meshFilters[i].sharedMesh;//存储网格
materials[i] = meshRenderers[i].sharedMaterial;//存储材质
combineInstances[i].transform = tr.worldToLocalMatrix * meshFilters[i].transform.localToWorldMatrix;//变换矩阵的问题,要保持相对位置不变,要转换为父节点的本地坐标,
//删除已经合并的原物体
if (meshFilters[i].gameObject.name != tr.gameObject.name)
{
Destroy(meshFilters[i].gameObject);
}
}
//构建新的网格
tr.GetComponent<MeshFilter>().mesh = new Mesh();
//传递保存下来的网格
tr.GetComponent<MeshFilter>().mesh.CombineMeshes(combineInstances,false);
//传递已经保存下来的材质
tr.GetComponent<MeshRenderer>().sharedMaterials = materials;
}