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)

相关推荐
平行云17 小时前
Enscape × Paraverse | 从设计到一键发布、网页分享、实时交互的全新体验
unity·ue5·xr·3dsmax·webgl·实时云渲染·云桌面
老朱佩琪!21 小时前
Unity迭代器模式
unity·设计模式·迭代器模式
程序猿多布1 天前
Unity 多语言系统实现
unity·多语言
CreasyChan1 天前
Unity中C#状态模式详解
unity·c#·状态模式
鹿野素材屋1 天前
动作游戏网游:帧同步下的动画同步
unity·游戏引擎
世洋Blog1 天前
数据驱动与MVC
unity·mvc
WMX10121 天前
Unity添加近身菜单-MRTK
unity·游戏引擎
在路上看风景2 天前
15. 纹理尺寸是4的倍数
unity
星依网络2 天前
使用LabelImg工具标注数据(游戏辅助脚本开发)
python·游戏引擎·图形渲染·骨骼绑定
AT~2 天前
unity 使用Socket和protobuf实现网络连接
unity·游戏引擎