Unity 动态合并网格纹理

该代码段展示了如何在Unity中合并多个子物体的Mesh并优化纹理内存使用。通过合并MeshFilter和MeshRenderer,创建新的材质,并将所有子物体的纹理合并到一张大图上,然后调整每个子物体的UV坐标以匹配新纹理的位置。最后,将合并的网格和纹理保存到指定路径,实现资源优化。
摘要由CSDN通过智能技术生成
    public static class MeshCombine
    {
        /// <summary>
        /// 图片缓存路径,这个路径在运行时不可访问,可以使用StreamAssets
        /// </summary>
        [SerializeField]
        private static string TGAPath = "Assets/Textures/texture.tga";
        /// <summary>
        /// material缓存路径,这个路径在运行时不可访问,可以使用StreamAssets
        /// </summary>
        [SerializeField]
        private static string MaterialPath = "Assets/Materials/mat.mat";
        /// <summary>
        /// 合并网格
        /// </summary>
        /// <param name="gameObject"></param>
        public static void CombineMesh(GameObject gameObject)
        {
            //获取所有子物体MeshFilter/MeshRenderer
            MeshFilter[] mfChildren = gameObject.GetComponentsInChildren<MeshFilter>();
            MeshRenderer[] mrChildren = gameObject.GetComponentsInChildren<MeshRenderer>();
            //组合的网格
            CombineInstance[] combine = new CombineInstance[mfChildren.Length];

            //在父物体上创建MeshFilter和MeshRenderer
            MeshRenderer mrSelf = gameObject.AddComponent<MeshRenderer>();
            MeshFilter mfSelf = gameObject.AddComponent<MeshFilter>();

            //创建一组材质球和纹理,并采集保存到数组
            Material[] materials = new Material[mrChildren.Length];
            Texture2D[] textures = new Texture2D[mrChildren.Length];
            for (int i = 0; i < mrChildren.Length; i++)
            {
                materials[i] = mrChildren[i].sharedMaterial;
                Texture2D tx = materials[i].GetTexture("_BaseMap") as Texture2D;
                Texture2D tx2D = new Texture2D(tx.width, tx.height, TextureFormat.ARGB32, false);
                tx2D.SetPixels(tx.GetPixels(0, 0, tx.width, tx.height));
                tx2D.Apply();
                textures[i] = tx2D;
            }
            //获取第一个材质,并拷贝参数,赋给父物体
            Material materialNew = new Material(materials[0].shader);
            materialNew.CopyPropertiesFromMaterial(materials[0]);
            mrSelf.sharedMaterial = materialNew;
            //创建一张纹理,并将纹理赋给父物体
            Texture2D texture = new Texture2D(1024, 1024);
            materialNew.SetTexture("_MainTex", texture);
            //将数组中的纹理保存在2d矩形空间中
            Rect[] rects = texture.PackTextures(textures, 10, 1024);

            for (int i = 0; i < mfChildren.Length; i++)
            {
                if (mfChildren[i].transform == gameObject.transform)
                {
                    continue;
                }
                Rect rect = rects[i];

                Mesh meshCombine = mfChildren[i].mesh;
                Vector2[] uvs = new Vector2[meshCombine.uv.Length];
                //把网格的uv根据贴图的rect刷一遍
                for (int j = 0; j < uvs.Length; j++)
                {
                    uvs[j].x = rect.x + meshCombine.uv[j].x * rect.width;
                    uvs[j].y = rect.y + meshCombine.uv[j].y * rect.height;
                }
                meshCombine.uv = uvs;
                combine[i].mesh = meshCombine;
                combine[i].transform = mfChildren[i].transform.localToWorldMatrix;
                mfChildren[i].gameObject.SetActive(false);
            }

            //合并网格
            Mesh newMesh = new Mesh();
            newMesh.CombineMeshes(combine, true, true);
            mfSelf.mesh = newMesh;


            FileWriteTexture(texture, TGAPath);
            CreateMaterial(materialNew);
            LoadTextureAlter(TGAPath);
            MaterialSetTexture(MaterialPath, TGAPath);
        }

        /// <summary>
        /// 把合并好的图片缓存对应在路径下
        /// </summary>
        /// <param name="texture"></param>
        static void FileWriteTexture(Texture2D texture, string jpgPath)
        {
            var bytes = texture.EncodeToTGA();
            FileStream file = File.Open(jpgPath, FileMode.Create);
            BinaryWriter writer = new BinaryWriter(file);
            writer.Write(bytes);
            file.Close();
            texture.Apply();
        }

        /// <summary>
        /// 合并后的材质球缓存到MaterialPath路径下,刷新
        /// </summary>
        /// <param name="materialNew"></param>
        static void CreateMaterial(Material materialNew)
        {
            AssetDatabase.CreateAsset(materialNew, MaterialPath);
            AssetDatabase.Refresh();
        }

        /// <summary>
        /// 加载缓存合并图片,修改里面的参数
        /// </summary>
        static void LoadTextureAlter(string path)
        {
            TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
            textureImporter.textureType = TextureImporterType.Default;
            textureImporter.isReadable = true;
            AssetDatabase.ImportAsset(path);
            AssetDatabase.Refresh();
        }

        /// <summary>
        /// 缓存的Material存在上面贴图丢失的现象,重新绑定贴图数据
        /// </summary>
        static void MaterialSetTexture(string materialPath, string jpgPath)
        {
            Material LoadMaterial = AssetDatabase.LoadAssetAtPath<Material>(materialPath);
            Texture2D Loadtextur = AssetDatabase.LoadAssetAtPath<Texture2D>(jpgPath);
            LoadMaterial.SetTexture("_MainTex", Loadtextur);
            AssetDatabase.Refresh();
        }
    }
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值