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)

相关推荐
深海潜水员5 小时前
【Behavior Tree】-- 行为树AI逻辑实现- Unity 游戏引擎实现
游戏·unity·c#
Thomas_YXQ14 小时前
Unity3D游戏内存优化指南
游戏·unity·职场和发展·性能优化·蓝桥杯·游戏引擎·unity3d
chillxiaohan15 小时前
Unity接入Steamworks.NET实现通信功能
unity
枯萎穿心攻击1 天前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎
X_StarX1 天前
【Unity笔记02】订阅事件-自动开门
笔记·学习·unity·游戏引擎·游戏开发·大学生
霸王•吕布1 天前
游戏引擎中顶点着色&像素着色
游戏引擎·顶点着色器·像素着色器·顶点颜色·顶点uv·顶点法向
一线灵2 天前
跨平台游戏引擎 Axmol-2.7.0 发布
c++·游戏引擎·wasm·axmol·cocos2dx
Thomas_YXQ2 天前
Unity URP法线贴图实现教程
开发语言·unity·性能优化·游戏引擎·unity3d·贴图·单一职责原则
徐子竣2 天前
[学习记录]Unity-Shader-几何着色器
unity·游戏引擎·着色器
EQ-雪梨蛋花汤2 天前
【Part 3 Unity VR眼镜端播放器开发与优化】第四节|高分辨率VR全景视频播放性能优化
unity·音视频·vr