ToB企服应用市场:ToB评测及商务社交产业平台

标题: Unity减少发布打包文件的体积(二)——设置WebGL发布时每张图片的压缩方式 [打印本页]

作者: 汕尾海湾    时间: 2024-10-18 23:12
标题: Unity减少发布打包文件的体积(二)——设置WebGL发布时每张图片的压缩方式
一个项目在发布成WebGL后,其体积至关紧张,体积太大,用户加载会履历一个漫长的等待…轻则骂娘,重则用脚把电脑踢烂(扣质保金)…
那么怎样减少发布后的体积呢,本文从图片的压缩开始入手。
前传回顾:
Unity减少发布打包文件的体积(一)——获取精灵图片的信息限制它的大小
一、徒手设置每张图片的压缩方法

在assets文件夹里选中一个Image,在Inspector底部有一个各发布平台的压缩设置,如下图中4的部分。
在此处设置压缩格式时,只针对发布时举行压缩,不会修改工程资源的原始文件,这样如果你发布成exe时,可以用高清的设置(而如果直接改了原始图片,则发布成exe时,画质被低落)。

1、压缩格式Format的说明(来源Claude.ai):


2、MaxSize的计算

Unity中如果你不单独设置,它的默认值大概就是2048,你可以写一个函数,根据分辨力来计算maxSize的值。

  1. /// <summary>
  2. /// 获取图片的分辨率,取分辨率中高宽的最大值,然后返回图片的【MaxSize】
  3. /// MaxSize的定义:assets->Image->【Texture2D ImportSettings】->【Override For WebGL】->【Max Size】
  4. /// 区间:16,32,64,128,256,512,1024,2048,4096,8192,16384
  5. ///
  6. /// 举例:图片分辨率 = 12 * 24,那么图片的MaxSize = 32
  7. /// </summary>
  8. /// <param name="texture"></param>
  9. /// <returns></returns>
  10. public static int GetMaxSize(Texture2D texture)
  11. {
  12.    //分辨率区间的预备
  13.    var start = new List<int> { 0, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384 };
  14.    var end = new List<int> { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 100000 };
  15.    var zones = start.Zip(end, (item1, item2) => (startIdx: item1, endIdx: item2)).ToList();
  16.    //取分辨率高宽的最大值
  17.    var size = new List<int> { texture.width, texture.height }.Max();  //取【宽】【高】中的最大值
  18.    //判断所属的区间
  19.    var maxSize = zones.First(x => x.startIdx <= size && size <= x.endIdx).endIdx;
  20.    //Debug.Log($"图的分辨率 = {texture.width} * {texture.height} size = {size}, MaxSize = {maxSize}");
  21.    return maxSize;
  22. }
复制代码
3、 Format的设置:

Unity面板上提供的各种压缩算法:

自己亲自指挥亲自摆设时,代码中可选的压缩格式:

4、提问:所有的图片能不能一键设置呢?

可以的,你可以自己写一个编辑器脚本(俗称插件),也可以让AI帮你写一个…然后自己慢慢改
二、一键设置所有图片的Build时的压缩选项

1、快捷菜单入口

右键全选图片 -> 【设置发布WebGL时贴图的压缩格式】

处置惩罚中…


2、压缩结果

压缩结束后,发现包的大小从230M减少到138兆。
3、实现的基本思绪


  1. Object[] textures = Selection.GetFiltered(typeof(Texture2D), SelectionMode.DeepAssets);
复制代码
留意:上述写法容易爆内存,如果我选取了2000多张图,有的图还是4k的,当图片加载的时间,内存暴涨,然后就是程序瓦解,电脑死机。使用场景就是只能选取少量的图片。
自动获取图片并处置惩罚:

  1. string[] guids = AssetDatabase.FindAssets("t:texture2d");
复制代码

  1. string path = AssetDatabase.GUIDToAssetPath(guid);//guid是guids的items
复制代码

  1. Texture2D texture = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
复制代码

  1. ......
复制代码

  1. // 创建特定平台压缩实例
  2. TextureImporterPlatformSettings platformSettings = new TextureImporterPlatformSettings();
  3. platformSettings.overridden = true;
  4. platformSettings.name = "WebGL";
  5. // 设置为压缩
  6. platformSettings.textureCompression = TextureImporterCompression.Compressed;
  7. // 设置压缩格式
  8. platformSettings.format = format;                                     //TextureImporterFormat.ASTC_12x12;
  9. platformSettings.compressionQuality = compressionQuality;             //40
  10. platformSettings.maxTextureSize = GetMaxSize(texture as Texture2D);   //32
  11. //设置importSettings
  12. TextureImporter importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)) as TextureImporter;
  13. importer.SetPlatformTextureSettings(platformSettings);
  14. //Apply 设置
  15. importer.SetPlatformTextureSettings(platformSettings);
  16. //保存资源
  17. importer.SaveAndReimport();
复制代码
三、附录(代码)

运行方式,放到任何Editor文件里
1、选中图片后右键菜单处置惩罚方式

  1. using System.Collections.Generic;using System.Linq;using UnityEngine;using UnityEditor;public class SetTextureCompression{    //****************************************参数设置区**********begin    //TODO 做成EditWindow类型    private static TextureImporterFormat format = TextureImporterFormat.ASTC_12x12;  //图片压缩格式    private static int compressionQuality = 60;                                      //压缩比例    private static string platform = "WebGL";                                        //发布的平台     //************************************************************end    /// <summary>    /// 设置贴图在build时的压缩选项    /// </summary>    [MenuItem("Assets/设置发布WebGL时贴图的压缩格式")]    static void SetCompression()    {        int count = 0;        Object[] textures = Selection.GetFiltered(typeof(Texture2D), SelectionMode.DeepAssets);
  2.         if (textures.Length > 0)        {            foreach (Object texture in textures)            {                // 创建特定平台压缩实例                TextureImporterPlatformSettings platformSettings = new TextureImporterPlatformSettings();                platformSettings.overridden = true;                platformSettings.name = platform;                // 设置为压缩                platformSettings.textureCompression = TextureImporterCompression.Compressed;                // 设置压缩格式                platformSettings.format = format;                                     //TextureImporterFormat.ASTC_12x12;                platformSettings.compressionQuality = compressionQuality;             //40                platformSettings.maxTextureSize = GetMaxSize(texture as Texture2D);   //32                //设置importSettings                TextureImporter importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)) as TextureImporter;                importer.SetPlatformTextureSettings(platformSettings);                //Apply 设置                importer.SetPlatformTextureSettings(platformSettings);                //生存资源                importer.SaveAndReimport();                count++;            }            //Debug.Log("Texture Compression Set!");        }        else        {            Debug.LogWarning("没有选中图片!");        }        Debug.Log($"一共处置惩罚了{count}张图片!");    }    /// <summary>    /// 获取图片的分辨率,取分辨率中高宽的最大值,然后返回图片的【MaxSize】    /// MaxSize的定义:assets->Image->【Texture2D ImportSettings】->【Override For WebGL】->【Max Size】     /// 区间:16,32,64,128,256,512,1024,2048,4096,8192,16384    ///    /// 举例:图片分辨率 = 12 * 24,那么图片的MaxSize = 32    /// </summary>    /// <param name="texture"></param>    /// <returns></returns>    static int GetMaxSize(Texture2D texture)    {        //分辨率区间的预备        var start = new List<int> { 0, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384 };        var end = new List<int> { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 100000 };        var zones = start.Zip(end, (item1, item2) => (startIdx: item1, endIdx: item2)).ToList();        //取分辨率高宽的最大值        var size = new List<int> { texture.width, texture.height }.Max();  //取【宽】【高】中的最大值        //判定所属的区间        var maxSize = zones            .First(x => x.startIdx <= size && size <= x.endIdx)            .endIdx;        //Debug.Log($"图的分辨率 = {texture.width} * {texture.height} size = {size}, MaxSize = {maxSize}");        return maxSize;    }}
复制代码
2、自动获取图片一键处置惩罚方式

关键代码【编辑器脚本使用】:
  1. using System;using UnityEngine;using UnityEditor;using System.Linq;using System.IO;using System.Collections.Generic;class Example : EditorWindow{#if UNITY_EDITOR    [MenuItem("模型处置惩罚/查找项目中所有的texture 2d对象并压缩")]#endif    static void FindAllTexture2D()    {        //****************************************参数设置区**********begin        //TODO 做成EditWindow类型        TextureImporterFormat format = TextureImporterFormat.ASTC_12x12; //图片压缩格式        int compressionQuality = 60; //压缩比例        string platform = "WebGL"; //发布的平台         //************************************************************end        //查找工程文件中的所有精灵图片        string[] guids = AssetDatabase.FindAssets("t:texture2d");
  2.         Debug.Log($"Found {guids.Length} Texture2d assets.");        foreach (string guid in guids)        {            try            {                string path = AssetDatabase.GUIDToAssetPath(guid);                Debug.Log($"{path}");                // 使用AssetDatabase加载Texture2D                Texture2D texture = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
  3.                 //Debug.Log($"{texture.name}");                if (texture == null) continue;                // 创建特定平台压缩实例                TextureImporterPlatformSettings platformSettings = new TextureImporterPlatformSettings();                platformSettings.overridden = true;                platformSettings.name = platform;                // 设置为压缩                platformSettings.textureCompression = TextureImporterCompression.Compressed;                // 设置压缩格式                platformSettings.format = format; //TextureImporterFormat.ASTC_12x12;                platformSettings.compressionQuality = compressionQuality; //40                platformSettings.maxTextureSize = GetMaxSize(texture as Texture2D); //32                //设置importSettings                TextureImporter importer =                    AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)) as TextureImporter;                if (importer == null) continue;                importer.SetPlatformTextureSettings(platformSettings);                //Apply 设置                importer.SetPlatformTextureSettings(platformSettings);                //生存资源                importer.SaveAndReimport();            }            catch (Exception ex)            {                Debug.Log( $" ~~~~~error~~~~~ 设置报错:{ex.Message}");            }        }    }    /// <summary>    /// 获取图片的分辨率,取分辨率中高宽的最大值,然后返回图片的【MaxSize】    /// MaxSize的定义:assets->Image->【Texture2D ImportSettings】->【Override For WebGL】->【Max Size】     /// 区间:16,32,64,128,256,512,1024,2048,4096,8192,16384    ///    /// 举例:图片分辨率 = 12 * 24,那么图片的MaxSize = 32    /// </summary>    /// <param name="texture"></param>    /// <returns></returns>    static int GetMaxSize(Texture2D texture)    {        //分辨率区间的预备        var start = new List<int> { 0, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384 };        var end = new List<int> { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 100000 };        var zones = start.Zip(end, (item1, item2) => (startIdx: item1, endIdx: item2)).ToList();        //取分辨率高宽的最大值        var size = new List<int> { texture.width, texture.height }.Max();  //取【宽】【高】中的最大值        //判定所属的区间        var maxSize = zones            .First(x => x.startIdx <= size && size <= x.endIdx)            .endIdx;        //Debug.Log($"图的分辨率 = {texture.width} * {texture.height} size = {size}, MaxSize = {maxSize}");        return maxSize;    }}
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4