Created
February 14, 2014 20:19
-
-
Save allanolivei/9008439 to your computer and use it in GitHub Desktop.
Unity 3d : Generating atlas(Sprites) of selected images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEditor; | |
using System.Collections; | |
public class AtlasGenerator { | |
//inseri no menu superior "Assets" a opcao de gerar um novo atlas das imagens selecionadas( Ctrl+Shift+C = %#c ) na raiz da pasta "Assets" | |
[MenuItem("Assets/GenerateAtlas %#c")] | |
static void Execute() | |
{ | |
//recupera todos as texturas selecionadas, inclusive aquelas que estao dentro das pastas selecionadas | |
Object[] objects = Selection.GetFiltered( typeof(Texture2D), SelectionMode.Assets | SelectionMode.DeepAssets ); | |
//se não obtiver nenhuma texture retorna uma mensagem | |
if( objects.Length == 0 ) | |
{ | |
EditorUtility.DisplayDialog("Error", "No images selected", "Ok"); | |
return; | |
} | |
//converte a lista de objetos e configura | |
Texture2D[] textures = new Texture2D[ objects.Length ]; | |
for( int i = 0 ; i < objects.Length ; i++ ) | |
textures[i] = AtlasGenerator.SetupTexture( objects[i] as Texture2D ); | |
//gera o atlas na raiz da pasta assets | |
AtlasGenerator.GenerateAtlas( textures ); | |
} | |
//configuracao basica para gerar o atlas | |
public static Texture2D SetupTexture( Texture2D texture ) { | |
//recupera os parametros de importação do objeto | |
string path = AssetDatabase.GetAssetPath( texture ); | |
TextureImporter texImp = (TextureImporter)AssetImporter.GetAtPath( path ); | |
texImp.textureType = TextureImporterType.Advanced; | |
//Para gerar o atlas é necessario que as imagens permitam a leitura e tenha o formato ARGB32 | |
texImp.isReadable = true; | |
texImp.textureFormat = TextureImporterFormat.ARGB32; | |
//atualiza as configuracoes | |
AssetDatabase.ImportAsset( path, ImportAssetOptions.ForceUpdate); | |
//returna a textura configurada | |
return texture; | |
} | |
//gera o atlas | |
public static void GenerateAtlas( Texture2D[] textures ) { | |
//Gera o atlas e recupera o mapeamento UV. | |
Texture2D texture = new Texture2D(1,1,TextureFormat.ARGB32,false); | |
Rect[] uvs = texture.PackTextures( textures, 2, 4096 ); | |
//cria um endereço único dentro da pasta Assets. | |
string path = AssetDatabase.GenerateUniqueAssetPath("Assets/atlas.png"); | |
//grava a imagem e destroi da memoria | |
System.IO.File.WriteAllBytes( path, texture.EncodeToPNG() ); | |
Object.DestroyImmediate(texture); | |
//atualiza a class AssetDatabase e todos os envolvidos, incluindo a janela Project. | |
AssetDatabase.Refresh(); | |
//carrega o arquivo gerado e suas configurações | |
Texture2D atlas = (Texture2D)AssetDatabase.LoadAssetAtPath( path, typeof(Texture2D) ); | |
TextureImporter texImp = (TextureImporter)AssetImporter.GetAtPath( path ); | |
float w = atlas.width; | |
float h = atlas.height; | |
//gerando todos os sprites | |
SpriteMetaData[] sprites = new SpriteMetaData[uvs.Length]; | |
for(int i = 0 ; i < uvs.Length ; i++ ) | |
{ | |
//converte uv para pixels | |
Rect uv = uvs[i]; | |
uv.x *= w; uv.y *= h; | |
uv.width *= w; uv.height *= h; | |
//gera o sprite | |
SpriteMetaData data = new SpriteMetaData(); | |
data.name = textures[i].name; | |
data.rect = uv; | |
sprites[i] = data; | |
} | |
//configura o atlas e passa as marcações dos sprites. | |
texImp.spritesheet = sprites; | |
texImp.textureType = TextureImporterType.Sprite; | |
texImp.spriteImportMode = SpriteImportMode.Multiple; | |
//atualiza as configurações | |
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate); | |
AssetDatabase.Refresh(); | |
//seleciona objeto gerado | |
Selection.activeObject = atlas; | |
//mensagem de sucesso | |
EditorUtility.DisplayDialog("Atlas Complete", "Generate Atlas Complete", "Ok"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment