把需要合并的网格统一放置到一个父节点下:
合并网格代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChinarMergeMesh : MonoBehaviour
{
void Start()
{
MergeMesh();
}
/// <summary>
/// 合并网格
/// </summary>
private void MergeMesh()
{
//获取所有子物体的网格
MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>();
//新建一个合并组,长度与Meshfilters一致
CombineInstance[] combineInstances = new CombineInstance[meshFilters.Length];
for (int i = 0; i < meshFilters.Length; i++)
{
combineInstances[i].mesh = meshFilters[i].sharedMesh;//将共享mesh,赋值
combineInstances[i].transform = meshFilters[i].transform.localToWorldMatrix;//本地坐标转矩阵,赋值
}
Mesh newMesh = new Mesh();
newMesh.CombineMeshes(combineInstances);
gameObject.AddComponent<MeshFilter>().sharedMesh = newMesh;
}
}