【Unity】【エディタ拡張】SpritePackerでpacking tagが付いているアトラスをすべてpngとして書き出す

SpritePackerでpacking tagが付いているアトラスをすべてpngとして書き出す方法です。

Unity2018.4.6

ソースコード

いきなりですがソースコードです。

using UnityEngine;
using UnityEditor;
using System.IO;
using UnityEditor.Sprites;

public static class BladeEditorUtility
{
    public static void OutputAtlasTextures(BuildTarget buildTarget)
    {
        // アトラスをリビルド
        Packer.RebuildAtlasCacheIfNeeded(buildTarget, true);

        // 全アトラステクスチャを取得して出力
        var folderPath = EditorUtility.SaveFolderPanel("Select Folder", string.Empty, string.Empty);
        if (!string.IsNullOrEmpty(folderPath)) {
            foreach (var atlasName in Packer.atlasNames) {
                var textures = Packer.GetTexturesForAtlas(atlasName);
                for (int i = 0; i < textures.Length; i++) {
                    SaveTexture(textures[i], folderPath);
                }
            }
        }
    }

    private static void SaveTexture(Texture2D src, string folderPath)
    {
        var filePath = Path.Combine(folderPath, src.name + ".png");

        // 一度RenderTextureに書き込む
        var renderTexture   = RenderTexture.GetTemporary(src.width, src.height, 0, RenderTextureFormat.ARGBFloat);
        Graphics.Blit(src, renderTexture);

        // RenderTextureの値をTextureに書きこむ
        var currentRT           = RenderTexture.active;
        RenderTexture.active    = renderTexture;
        var dest             = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGBAFloat, false);
        dest.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        dest.Apply();
        RenderTexture.active    = currentRT;

        // ファイル書き込み
        File.WriteAllBytes(filePath, dest.EncodeToPNG());
        AssetDatabase.Refresh();

        // RenderTextureを解放
        RenderTexture.ReleaseTemporary(renderTexture);
    }
}

旧Sprite PackerのAPIにはUnityEditor.Sprites.Packerからアクセスできます。

これを実行してフォルダを選択するとすべてのアトラスがpngとして出力されます。