ArrayList materials = new ArrayList();
ArrayList combineInstanceArrays = new ArrayList();</pre>下面我们开始遍历我们需要优化对象的MeshFilter和MeshRenderer,因为材质是与MeshRenderder相关联的代码如下:<pre class="brush:c#;toolbar:false"> foreach (GameObject obj in Objects)
{
if (!obj)
continue;
foreach (MeshFilter meshFilter in meshFilters)
{
MeshRenderer meshRenderer = meshFilter.GetComponent<MeshRenderer>();
if (!meshRenderer)
{
Debug.LogError("MeshFilter does not have a coresponding MeshRenderer.");
continue;
}
if (meshRenderer.materials.Length != meshFilter.sharedMesh.subMeshCount)
{
Debug.LogError("Mismatch between material count and submesh count. Is this the correct MeshRenderer?");
continue;
}
for (int s = 0; s < meshFilter.sharedMesh.subMeshCount; s++)
{
int materialArrayIndex = 0;
for (materialArrayIndex = 0; materialArrayIndex < materials.Count; materialArrayIndex++)
{
if (materials[materialArrayIndex] == meshRenderer.sharedMaterials[s])
break;
}
if (materialArrayIndex == materials.Count)
{
materials.Add(meshRenderer.sharedMaterials[s]);
combineInstanceArrays.Add(new ArrayList());
}
Mesh[] meshes = new Mesh[materials.Count];
CombineInstance[] combineInstances = new CombineInstance[materials.Count];
for (int m = 0; m < materials.Count; m++)
{
CombineInstance[] combineInstanceArray = (combineInstanceArrays[m] as ArrayList).ToArray(typeof(CombineInstance)) as CombineInstance[];
meshes[m] = new Mesh();
meshes[m].CombineMeshes(combineInstanceArray, true, true);