"If you do nothing, nothing will happen."

프로그래밍

[Unity3D] UGUI 아틀라스에서 Sprite 파일 분리하기

tedhong 2023. 2. 20. 12:48
2018-03-28 글쓴이 TED HONG

[Unity3D] UGUI 아틀라스에서 Sprite 파일 분리하기

이미 합쳐져 있는 UGUI용 Atlas File 에서 Sprite 를 분리하는 방법

Atlas 의  Texture로 부터
Sprite 영역만큼 Pixel 값을 가져와
새로운 Texture에 입히고 
파일로 저장하면 됩니다.

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

public class AtlasLoader
{
    public Dictionary<string, Sprite> spriteDic = new Dictionary<string, Sprite>();

    public AtlasLoader()
    {

    }

    public AtlasLoader(string spriteBaseName)
    {
        loadSprite(spriteBaseName);
    }

    //Loads the provided sprites
    public void loadSprite(string spriteBaseName)
    {
        Sprite[] allSprites =  Resources.LoadAll<Sprite>(spriteBaseName);
        if (allSprites == null || allSprites.Length <= 0)
        {
            Debug.LogError("The Provided Base-Atlas Sprite `" + spriteBaseName + "` does not exist!");
            return;
        }

        for (int i = 0; i < allSprites.Length; i++)
        {
            spriteDic.Add(allSprites[i].name, allSprites[i]);
            MakeFile(allSprites[i]);
        }
    }

    void MakeFile(Sprite sprite)
    {
        try
        {
            Debug.Log(string.Format("{0} : {1}", sprite.name, sprite.rect.ToString()));
            Rect rect = sprite.rect; //분리할 스프라이트의 시작 좌표와 사이즈
            Texture2D mainTex = sprite.texture; //스프라이트의 메인 텍스쳐를 가져옴
            //새로 만들어질 텍스쳐, sprite.texture.format 이건 메인 텍스쳐의 포맷을 그대로 사용
            Texture2D tex = new Texture2D((int)rect.width, (int)rect.height, sprite.texture.format, false); 
            //메인 텍스쳐에서 스프라이트의 영역 만큼 픽셀 값을 가져옴
            Color[] c = mainTex.GetPixels((int)rect.x, (int)rect.y, (int)rect.width, (int)rect.height);
            tex.SetPixels(c);// 새 텍스쳐에 픽셀값을 입힘
            tex.Apply(); // 적용
            var bytes = tex.EncodeToPNG(); // PNG byte로 형태로 만듬. JPG는 EncodeToJPG 사용 
            string savePath = string.Format("{0}/{1}.png", Application.persistentDataPath, sprite.name); //저장할 파일 위치
            Object.DestroyImmediate(tex, true); //새텍스쳐는 쓸일이 없으므로 삭제
            System.IO.File.WriteAllBytes(savePath, bytes); //파일로 쓰기
            Debug.Log("MakeFile : " + sprite.name);
        }
        catch (System.Exception ex)
        {

        }

    }
}

#Split_sprite_file_from_UGUI_atlas_file.