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)

相关推荐
郁闷的网纹蟒34 分钟前
虚幻5---第12部分---蒙太奇
开发语言·c++·ue5·游戏引擎·虚幻
天人合一peng1 小时前
Unity 中Canvas 或image打勾时不显示
unity
淡海水1 天前
【节点】[Houndstooth节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·houndstooth
微:xsooop2 天前
iOS上架被拒4.3(a) 10次到过审历程
flutter·unity·ios·uniapp
DoomGT2 天前
Physics Simulation - Hit Event的触发机制
ue5·游戏引擎·虚幻·虚幻引擎·unreal engine
jtymyxmz2 天前
《Unity Shader》14.1 卡通风格的渲染
unity·游戏引擎
天人合一peng2 天前
unity获得和修改button的text(TMP)
java·前端·unity
dzj20213 天前
Unity中使用LLMUnity遇到的问题(三)——如何配置和使用知识库
unity·llmunity·知识库大模型
Clank的游戏栈3 天前
Unity自动化美术资源校验工具(模型/材质规范检测)技术详解
unity·自动化·材质
Sator13 天前
Unity烘焙光打包后光照丢失问题
unity·光照贴图