Unity3D静态对象优化系列三

 

我们接着系列二的问题继续讲解,系列二中的问题是如果多个材质是相同的,它没有去优化,接下来我们将其优化一下,首先要找到在哪里去优化,我们看下面的for循环语句也是系列二的代码,如下:


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());
}
CombineInstance combineInstance = new CombineInstance();
combineInstance.transform = meshRenderer.transform.localToWorldMatrix;
combineInstance.subMeshIndex = s;
combineInstance.mesh = meshFilter.sharedMesh;
(combineInstanceArrays[materialArrayIndex] as ArrayList).Add(combineInstance);
}

这个代码里它没有判断是否有相同的材质,接下来我们将其重新修改一下:


for (int s = 0; s < meshFilter.sharedMesh.subMeshCount; s++)
{
int materialArrayIndex = Contains(materials, meshRenderer.sharedMaterials[s].name);
if (materialArrayIndex == -1)
{
materials.Add(meshRenderer.sharedMaterials[s]);
materialArrayIndex = materials.Count - 1;
}
combineInstanceArrays.Add(new ArrayList());
CombineInstance combineInstance = new CombineInstance();
combineInstance.transform = meshRenderer.transform.localToWorldMatrix;
combineInstance.subMeshIndex = s;
combineInstance.mesh = meshFilter.sharedMesh;
(combineInstanceArrays[materialArrayIndex] as ArrayList).Add(combineInstance);
}

我们看到上面有个函数Contains它就是用于判断是否有相同的材质,如果有就作为一张材质,Contains函数代码如下所示:


private int Contains(ArrayList searchList, string searchName)

{

for (int i = 0; i < searchList.Count; i++)

{

if (((Material)searchList[i]).name == searchName)

{

return i;

}

}

return -1;

}

作用是用于返回相同材质的索引,效果如下:

wKiom1S9uuXjP3PvAAYPkBx1Gig256.jpg

看上图红色的部分,有两个材质是一样的,材质只显示一个了,将其优化了。整个静态对象的优化就给大家解答完了。

作者:大洋    博客:http://jxwgame.blog.51cto.com