Unity动态对象优化–Dynamic Combine

 

对于静态对象,Unity可以使用通过勾选Static,然后让Unity自身进行优化Draw Calls,但是对于动态对象,Unity在这方面没有处理,这就需要我们自己去实现,实现的原理就是首先去遍历每个对象的 SkinnderMeshRenderer,然后将其所有的动态对象组合成一个大的对象并且将骨骼动画赋值给他,这样,我们就实现了动态对象的优化,代码 如下:


public static void CombineToMesh(GameObject _go)
{
SkinnedMeshRenderer[] _smr = _go.GetComponentsInChildren<SkinnedMeshRenderer>();
List<CombineInstance> lcom = new List<CombineInstance>();

List<Material> lmat = new List<Material>();
List<Transform> ltra = new List<Transform>();

for (int i = 0; i < _smr.Length; i++)
{
lmat.AddRange(_smr[i].materials);
ltra.AddRange(_smr[i].bones);

for (int sub = 0; sub < _smr[i].sharedMesh.subMeshCount; sub++ )
{
CombineInstance ci = new CombineInstance();
ci.mesh = _smr[i].sharedMesh;
ci.subMeshIndex = sub;
lcom.Add(ci);
}
Destroy(_smr[i].gameObject);

}

SkinnedMeshRenderer _r = _go.GetComponent<SkinnedMeshRenderer>();
if (_r == null)
_r = _go.AddComponent<SkinnedMeshRenderer>();
_r.sharedMesh = new Mesh();
_r.bones = ltra.ToArray();
_r.materials = new Material[] { lmat[0] };
_r.rootBone = _go.transform;

_r.sharedMesh.CombineMeshes(lcom.ToArray(), true, false);

}

以上是完整的源代码,大家只要将其调用即可。本文转载自CSDN,

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