Unity Mesh合并
程序员文章站
2022-03-18 17:11:32
...
public class CombineTest : MonoBehaviour
{
public GameObject model;
void Start() {
Debug.Log(Time.realtimeSinceStartup);
MeshFilter[] meshFilters = model.GetComponentsInChildren<MeshFilter>();
Dictionary<string, List<CombineInstance>> combines = new Dictionary<string, List<CombineInstance>>();
List<Material> mats = new List<Material>();
List<CombineInstance> combineList = new List<CombineInstance>();
for (int i = 0; i < meshFilters.Length; i++) {
for (int j = 0; j < meshFilters[i].sharedMesh.subMeshCount; j++) {
CombineInstance ci = new CombineInstance();
MeshRenderer render = meshFilters[i].GetComponent<MeshRenderer>();
Mesh m = Instantiate(meshFilters[i].sharedMesh);
ci.mesh = m;
ci.transform = meshFilters[i].transform.localToWorldMatrix;
//ci.mesh.SetIndices(meshFilters[i].sharedMesh.GetIndices(j), meshFilters[i].sharedMesh.GetTopology(j), 0);
ci.mesh.SetTriangles(meshFilters[i].sharedMesh.GetTriangles(j), 0);
if (!combines.ContainsKey(render.materials[j].name)) {
combines.Add(render.materials[j].name, new List<CombineInstance>() { ci });
mats.Add(render.materials[j]);
} else {
combines[render.materials[j].name].Add(ci);
}
}
}
Material[] matss = mats.ToArray();
for (int i = 0;i < combines.Keys.Count; i++) {
Mesh mesh01 = new Mesh();
var com = combines[combines.Keys.ToArray()[i]].ToArray();
mesh01.CombineMeshes(com, true);
GameObject go1 = new GameObject();
go1.AddComponent<MeshFilter>();
go1.GetComponent<MeshFilter>().mesh = mesh01;
go1.AddComponent<MeshRenderer>();
go1.GetComponent<MeshRenderer>().material = matss[i];
go1.SetActive(false);
CombineInstance cccc = new CombineInstance();
cccc.mesh = mesh01;
cccc.transform = go1.transform.localToWorldMatrix;
combineList.Add(cccc);
Destroy(go1);
}
Mesh mesh = new Mesh();
var comL = combineList.ToArray();
mesh.CombineMeshes(comL, false);
GameObject go = new GameObject();
go.AddComponent<MeshFilter>();
go.GetComponent<MeshFilter>().mesh = mesh;
go.AddComponent<MeshRenderer>();
go.GetComponent<MeshRenderer>().materials = matss;
Debug.Log(Time.realtimeSinceStartup);
}
}