Unity 輸出圖集中的圖片

1、大圖導入unity,修改配置

Texture Type:Sprite(2D and UI)

Sprite Mode:Multiple

Read/Write enabled:true

format:RGBA 32 bit

腳本如下:

using UnityEngine;
using UnityEditor;

public class Tools
{
    [MenuItem("Tools/AtlasToSprite")]
    public static void AtlasToSprite()
    {
        string out_path = "E:/Program/outSprite/";//圖集最後輸出路徑
        string resourcesPath = "Assets/Resources/";//因爲使用的是Resources.LoadAll加載只能放這個目錄下
        Object[] selects = Selection.objects;
        if(selects.Length < 1)
        {
            Debug.LogError("未選中文件");
            return;
        }
        for(int index = 0; index < selects.Length; index++)
        {
            string select_path = AssetDatabase.GetAssetPath(selects[index]);
            if (!select_path.StartsWith(resourcesPath))
            {
                Debug.LogWarning("未在Assets.Resources目錄下 path:"+select_path);
                continue;
            }
            
            string select_ext = System.IO.Path.GetExtension(select_path);
            if (!select_ext.Equals(".png"))
            {
                Debug.LogWarning("選中文件非png path:" + select_path);//默認就png吧  看需求改咯
                continue;
            }
            
            string load_path = select_path.Remove(select_path.Length - select_ext.Length);
            load_path = load_path.Substring(resourcesPath.Length);

            Sprite[] sprites = Resources.LoadAll<Sprite>(load_path);//加載到圖集下所有sprite
            if (sprites.Length < 1)
            {
                Debug.Log("非sprite path:"+select_path);
                continue;
            }

            string outPath = out_path + load_path;
            System.IO.Directory.CreateDirectory(outPath);//創建目錄

            foreach (Sprite sprite in sprites)
            {
                Texture2D tex = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height, sprite.texture.format, false);
                tex.SetPixels(sprite.texture.GetPixels((int)sprite.rect.xMin, (int)sprite.rect.yMin, (int)sprite.rect.width, (int)sprite.rect.height));
                tex.Apply();
                System.IO.File.WriteAllBytes(outPath + "/" + sprite.name + ".png", tex.EncodeToPNG());//導出png
            }
        }
    }
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章