Unity性能优化---动态网格组合(二)

在上一篇中,组合的是同一个材质球的网格,如果其中有不一样的材质球会发生什么?如下图:

将场景中的一个物体替换为不同的材质球

运行之后,就变成了相同的材质。

要实现组合不同材质的网格步骤如下:

在父物体上添加不同的材质球,

然后在组合时,先将相同材质的物体组合,再将不同材质的物体组合,但是组合为一个mesh后,因为是两个材质球,会调用绘制两次。

代码如下

cs 复制代码
public class MeshCombine2 : MonoBehaviour
{
    public GameObject[] obj1;
    public GameObject[] obj2;

    public void Start()
    {
        this.MeshCombine();
    }

    void MeshCombine()
    {
        MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>();
        List<CombineInstance> combine1 = new List<CombineInstance>(obj1.Length);
        List<CombineInstance> combine2 = new List<CombineInstance>(obj2.Length);

        for (int j = 0; j < meshFilters.Length; j++)
        {
            MeshFilter meshFilter = meshFilters[j];
            CombineInstance l_combine = new CombineInstance();
            MeshRenderer meshRender = meshFilter.GetComponent<MeshRenderer>();
            string materialName = meshRender.material.name.Replace(" (Instance)", "");
            if (materialName == "Grass")
            {
                l_combine.mesh = meshFilter.mesh;
                l_combine.transform = meshFilter.transform.localToWorldMatrix;
                combine2.Add(l_combine);
            }
            else
            {
                l_combine.mesh = meshFilter.mesh;
                l_combine.transform = meshFilter.transform.localToWorldMatrix;
                combine1.Add(l_combine);
            }
            meshFilter.gameObject.SetActive(false);
        }
        Mesh obj1Mesh = new Mesh();
        obj1Mesh.CombineMeshes(combine1.ToArray());

        Mesh obj2Mesh = new Mesh();
        obj2Mesh.CombineMeshes(combine2.ToArray());

        CombineInstance[] combine = new CombineInstance[2];

        combine[0].mesh = obj1Mesh;
        combine[0].transform = this.transform.localToWorldMatrix;
        combine[1].mesh = obj2Mesh;
        combine[1].transform = this.transform.localToWorldMatrix;

        Mesh mesh = new Mesh();
        mesh.CombineMeshes(combine,false);
        transform.GetComponent<MeshFilter>().sharedMesh = mesh;
        transform.gameObject.SetActive(true);
    }
}

参考链接:

Unity 与 C# 中的动态网格组合 - 组合不同颜色的网格 |哈布拉多 (habrador.com)

相关推荐
我的offer在哪里6 小时前
示例 Unity 项目结构(Playable Game Template)
unity·游戏引擎
淡海水8 小时前
【节点】[Branch节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·branch
在路上看风景8 小时前
4.6 显存和缓存
unity
Zik----11 小时前
简单的Unity漫游场景搭建
unity·游戏引擎
在路上看风景21 小时前
4.5 顶点和片元
unity
在路上看风景1 天前
31. Unity 异步加载的底层细节
unity
天人合一peng1 天前
Unity中做表头时像work中整个调整宽窄
unity
小李也疯狂2 天前
Unity 中的立方体贴图(Cubemaps)
unity·游戏引擎·贴图·cubemap
牛掰是怎么形成的2 天前
Unity材质贴图引用陷阱:包体暴涨真相
unity·材质·贴图
呆呆敲代码的小Y2 天前
【Unity工具篇】| 超实用工具LuBan,快速上手使用
游戏·unity·游戏引擎·unity插件·luban·免费游戏·游戏配置表