当前位置:网站首页>Unity dynamically merges mesh textures

Unity dynamically merges mesh textures

2022-07-07 23:01:00 weixin_ forty-four million four hundred and eighty-nine thousan

    public static class CarControlMeshCombine
    {
    
        /// <summary>
        ///  Picture cache path , This path is not accessible at runtime , have access to StreamAssets
        /// </summary>
        [SerializeField]
        private static string TGAPath = "Assets/ArtAssets/A_3D/Cars/LicensePlates/Textures/texture.tga";
        /// <summary>
        /// material Cache path , This path is not accessible at runtime , have access to StreamAssets
        /// </summary>
        [SerializeField]
        private static string MaterialPath = "Assets/ArtAssets/A_3D/Cars/LicensePlates/Materials/mat.mat";
        /// <summary>
        ///  Merge grids 
        /// </summary>
        /// <param name="gameObject"></param>
        public static void CombineMesh(GameObject gameObject)
        {
    
            // Get all sub objects MeshFilter/MeshRenderer
            MeshFilter[] mfChildren = gameObject.GetComponentsInChildren<MeshFilter>();
            MeshRenderer[] mrChildren = gameObject.GetComponentsInChildren<MeshRenderer>();
            // Combined mesh 
            CombineInstance[] combine = new CombineInstance[mfChildren.Length];

            // Create on the parent object MeshFilter and MeshRenderer
            MeshRenderer mrSelf = gameObject.AddComponent<MeshRenderer>();
            MeshFilter mfSelf = gameObject.AddComponent<MeshFilter>();

            // Create a set of shaders and textures , And collect and save to the array 
            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;
            }
            // Get the first material , And copy the parameters , Assign to parent object 
            Material materialNew = new Material(materials[0].shader);
            materialNew.CopyPropertiesFromMaterial(materials[0]);
            mrSelf.sharedMaterial = materialNew;
            // Create a texture , And assign the texture to the parent object 
            Texture2D texture = new Texture2D(1024, 1024);
            materialNew.SetTexture("_MainTex", texture);
            // Save the texture in the array in 2d In rectangular space 
            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];
                // Put the grid uv According to the mapping rect Brush once 
                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);
            }

            // Merge grids 
            Mesh newMesh = new Mesh();
            newMesh.CombineMeshes(combine, true, true);
            mfSelf.mesh = newMesh;


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

        /// <summary>
        ///  Cache the merged pictures under the path 
        /// </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>
        ///  The merged shaders are cached in MaterialPath Under the path , Refresh 
        /// </summary>
        /// <param name="materialNew"></param>
        static void CreateMaterial(Material materialNew)
        {
    
            AssetDatabase.CreateAsset(materialNew, MaterialPath);
            AssetDatabase.Refresh();
        }

        /// <summary>
        ///  Load cache merge pictures , Modify the parameters inside 
        /// </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>
        ///  The cache Material There is a phenomenon that the above map is missing , Rebind map data 
        /// </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();
        }
    }
原网站

版权声明
本文为[weixin_ forty-four million four hundred and eighty-nine thousan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071915060041.html