unity 图片格式一键修改

  1. unity 可以通过修改图片格式来减少包体大小,不同平台对不用格式图片的加载速度,也有差别.在开发WebGl是因为没有开发好的工具,要对图片进行一个处理,自己写了一个脚本工具类,来进行图片适配WebGl端.
  2. 最后的效果,用过选择文件夹来处理文件夹下的图片,不用人工一张一张设置了.

代码:

先创建一个TextureImportChanging类,继承EditorWindow类.

主要方法:先设置一个设置图片格式的界面,

using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Hardware;

public class TextureImportChanging : EditorWindow
{
    enum MaxSize
    {
        Size_32 = 32,
        Size_64 = 64,
        Size_128 = 128,
        Size_256 = 256,
        Size_512 = 512,
        Size_1024 = 1024,
        Size_2048 = 2048,
        Size_4096 = 4096,
        Size_8192 = 8192,

    }
    private string platformName
    {
        get
        {
#if UNITY_WEBGL
            return "WebGL";
#else
            return "Default";
#endif
        }
    }

    private static TextureImporterFormat textureImporterFormat
    {
        get
        {
#if UNITY_WEBGL
            return TextureImporterFormat.DXT5Crunched;
#else
            return TextureImporterFormat.Automatic;
#endif
        }
    }
    // ----------------------------------------------------------------------------  
    TextureImporterType textureType = TextureImporterType.Sprite;

    static TextureImporterFormat textureFormat = textureImporterFormat;

    MaxSize textureSize = MaxSize.Size_1024;

    TextureImporterCompression textureCompression = TextureImporterCompression.Uncompressed;

    static TextureWrapMode wrapMode = TextureWrapMode.Repeat;

    static FilterMode filterMode = FilterMode.Bilinear;
    bool ifAllowsAlphaSplitting = true;
    static bool ifMipmapEnabled = false;

    /// <summary>
    /// 是否重置图片属性
    /// </summary>
    static bool textureModifier = true;
    /// <summary>
    /// 是否改变图片类型
    /// </summary>
    bool isChangeTextureType = false;
    /// <summary>
    /// 是否固定的改变图片格式
    /// </summary>
    static bool isChangeTexturFormat = true;

    // float secs = 10.0f;
    // double startVal = 0;
    // float progress = 0f;

    static TextureImportChanging window;

    [@MenuItem("资源管理/设置图片格式")]
    private static void Init()
    {
        Rect wr = new Rect(0, 0, 400, 400);
        window = (TextureImportChanging)EditorWindow.GetWindowWithRect(typeof(TextureImportChanging), wr, false, "图片格式设置");
        window.Show();
    }

    private void OnGUI()
    {
        EditorGUILayout.Space();
        EditorGUILayout.HelpBox("设置选中图片或选中路径下的图片属性", MessageType.Info);
        EditorGUILayout.Space();

        isChangeTextureType = EditorGUILayout.Toggle("是否改变图片类型:", isChangeTextureType);
        if (isChangeTextureType)
            textureType = (TextureImporterType)EditorGUILayout.EnumPopup("类型:", textureType);
        EditorGUILayout.Space();

        isChangeTexturFormat = EditorGUILayout.Toggle("是否固定改变图片格式:", isChangeTexturFormat);
        if (isChangeTexturFormat)
            textureFormat = (TextureImporterFormat)EditorGUILayout.EnumPopup("格式:", textureFormat);
        EditorGUILayout.Space();

        textureCompression = (TextureImporterCompression)EditorGUILayout.EnumPopup("压缩:", textureCompression);

        ifAllowsAlphaSplitting = EditorGUILayout.Toggle("是否允许透明分离:", ifAllowsAlphaSplitting);
        ifMipmapEnabled = EditorGUILayout.Toggle("是否允许Mipmap:", ifMipmapEnabled);
        textureModifier = EditorGUILayout.Toggle("是否重置图片属性:", textureModifier);

        if (!textureModifier)
        {
            EditorGUILayout.Space();
            EditorGUILayout.HelpBox("如果有导入自动设置图片脚本,下面方法未必执行", MessageType.Info);
            EditorGUILayout.Space();
            textureSize = (MaxSize)EditorGUILayout.EnumPopup("尺寸:", textureSize);
            wrapMode = (TextureWrapMode)EditorGUILayout.EnumPopup("wrapMode:", wrapMode);
            filterMode = (FilterMode)EditorGUILayout.EnumPopup("filterMode:", filterMode);
        }

        EditorGUILayout.Space();

        if (GUILayout.Button("设置"))
        {
            TextureImporterPlatformSettings t = new TextureImporterPlatformSettings();
            t.allowsAlphaSplitting = ifAllowsAlphaSplitting;
            t.format = textureFormat;
            t.maxTextureSize = (int)textureSize;
            t.textureCompression = textureCompression;

            SelectedChangeTextureFormatSettings(t, textureType, GetSelectedTextures());
        }

        //if (GUILayout.Button("一键设置(Textures目录)")) {
        //    TextureImporterPlatformSettings t = new TextureImporterPlatformSettings();

        //    t.allowsAlphaSplitting = ifAllowsAlphaSplitting;
        //    t.format = textureFormat;

        //    t.maxTextureSize = (int)textureSize;
        //    t.textureCompression = textureCompression;

        //    SelectedChangeTextureFormatSettings(t, textureType,GetTexture());
        //}

    }

    /// <summary>
    /// 开始修改图片
    /// </summary>
    /// <param name="_t"></param>
    /// <param name="_type"></param>
    /// <param name="arr"></param>
    void SelectedChangeTextureFormatSettings(TextureImporterPlatformSettings _t, TextureImporterType _type, Object[] arr)
    {

        Object[] textures = arr;
        if (window == null)
            Init();
        if (textures != null)
        {
            if (textures.Length < 1)
            {
                window.ShowNotification(new GUIContent("找不到图片!"));
                return;
            }
        }
        else
        {
            window.ShowNotification(new GUIContent("请选中图片或路径!"));
            return;
        }
        Selection.objects = new Object[0];
        int i = 0;
        foreach (Texture2D texture in textures)
        {
            string path = AssetDatabase.GetAssetPath(texture);
            //dds格式的图片不在本次修改范围内
            if (path.Substring(path.Length - 3, 3) == "dds")
                continue;
            string[] pathArr = path.Split('/');

            TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
           // Debug.Log(textureImporter.DoesSourceTextureHaveAlpha());
            if (isChangeTextureType)
                textureImporter.textureType = _type;

            textureImporter.allowAlphaSplitting = _t.allowsAlphaSplitting;
            textureImporter.mipmapEnabled = ifMipmapEnabled;
            textureImporter.borderMipmap = ifMipmapEnabled;

            if (!textureModifier)
            {
                textureImporter.maxTextureSize = _t.maxTextureSize;
                textureImporter.wrapMode = wrapMode;
                textureImporter.filterMode = filterMode;
                textureImporter.spritePackingTag = pathArr[pathArr.Length - 2];
                TextureImporterPlatformSettings platFormat = new TextureImporterPlatformSettings
                {
                    name = platformName,
                    overridden = true,
                    format = GetFormat(textureImporter),
                    maxTextureSize = _t.maxTextureSize
                };
                textureImporter.SetPlatformTextureSettings(platFormat);
            }

            ShowProgress((float)i / (float)textures.Length, textures.Length, i);
            i++;
            AssetDatabase.ImportAsset(path);
        }
        //刷新
        AssetDatabase.Refresh();
        EditorUtility.ClearProgressBar();
        textures = null;
    }
    /// <summary>
    /// 设置修改进度
    /// </summary>
    /// <param name="val"></param>
    /// <param name="total"></param>
    /// <param name="cur"></param>
    public static void ShowProgress(float val, int total, int cur)
    {
        EditorUtility.DisplayProgressBar("设置图片中...", string.Format("请稍等({0}/{1}) ", cur, total), val);
    }

    //获取选中文件夹下所有的Texture2D图片(包含文件夹下的文件夹)
    static Object[] GetSelectedTextures()
    {
        return Selection.GetFiltered(typeof(Texture2D), SelectionMode.DeepAssets);
    }

    /// <summary>
    /// 判断是否含有透明通道,动态返回
    /// TextureImporterFormat.DXT5Crunched或TextureImporterFormat.DXT1Crunched;
    /// 有的图片不包含上诉两种图片格式(可以添加個判斷,現在沒有添加)
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    static TextureImporterFormat GetFormat(TextureImporter item)
    {
        if (isChangeTexturFormat)
            return textureFormat;
        else
        {
            return item.DoesSourceTextureHaveAlpha()?  TextureImporterFormat.DXT5Crunched: TextureImporterFormat.DXT1Crunched;
        }

    }


    void OnInspectorUpdate()
    {
        Repaint();
    }

}

第一次写这种工具,也是在别人的基础上修改的,有大佬可以指出里面逻辑不对的地方

猜你喜欢

转载自blog.csdn.net/weixin_42129718/article/details/115128569
今日推荐