Unity自身进行优化Draw Calls,但是对于动态对象,Unity在这方面没有处理,这就需要我们自己去实现,实现的原理就是首先

去遍历每个对象的SkinnderMeshRenderer,然后将其所有的动态对象组合成一个大的对象并且将骨骼动画赋值给他,这样,我们

就实现了动态对象的优化



[C#] 纯文本查看 复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
publicstaticvoidCombineToMesh(GameObject _go)
    {
        SkinnedMeshRenderer[] _smr = _go.GetComponentsInChildren<SkinnedMeshRenderer>();
        List<CombineInstance> lcom =newList<CombineInstance>();
 
        List<Material> lmat =newList<Material>();
        List<Transform> ltra =newList<Transform>();
 
        for(inti = 0; i < _smr.Length; i++)
        {
            lmat.AddRange(_smr.materials);
            ltra.AddRange(_smr.bones);
 
            for(intsub = 0; sub < _smr.sharedMesh.subMeshCount; sub++ )
            {
                CombineInstance ci =newCombineInstance();
                ci.mesh = _smr.sharedMesh;
                ci.subMeshIndex = sub;
                lcom.Add(ci);
            }
            Destroy(_smr.gameObject);
 
        }
 
        SkinnedMeshRenderer _r = _go.GetComponent<SkinnedMeshRenderer>();
        if(_r ==null)
            _r = _go.AddComponent<SkinnedMeshRenderer>();
        _r.sharedMesh =newMesh();
        _r.bones = ltra.ToArray();
        _r.materials =newMaterial[] { lmat[0] };
        _r.rootBone = _go.transform;
 
        _r.sharedMesh.CombineMeshes(lcom.ToArray(),true,false);
 
    }