public static void refreshSourceImages( this SKSpriteSheet sheet )
{
// set a flag while we import the PSD to avoid our AssetPostprocessor from getting an endless loop of death
isCurrentlyRefreshingSourceImages = true;
try
{
var textureInfoList = new List<SKTextureInfo>();
var files = Directory.GetFiles( sheet.imageSourceFolder ).Where( f => !f.EndsWith( ".meta" ) ).ToArray();
var textures = new Dictionary<string,Texture2D>( files.Length );
var texturesNotToDestroy = new List<string>();
var containedImages = new List<string>();
float progress = 1f;
foreach( var f in files )
{
EditorUtility.DisplayProgressBar( "Creating Sprite Atlases..", "processing image at path: " + f, progress++ / files.Length );
var path = Path.Combine( sheet.imageSourceFolder, Path.GetFileName( f ) );
Texture2D tex = null;
if( Path.GetExtension( path ) == ".png" )
{
// we load directly from disk so that the textures are guaranteed readable
tex = new Texture2D( 0, 0 );
tex.LoadImage( File.ReadAllBytes( f ) );
}
else if( Path.GetExtension( path ).ToLower() == ".psd" || Path.GetExtension( path ) == ".gif" )
{
var texImporter = TextureImporter.GetAtPath( path ) as TextureImporter;
texImporter.isReadable = true;
AssetDatabase.ImportAsset( path );
tex = AssetDatabase.LoadAssetAtPath( path, typeof( Texture2D ) ) as Texture2D;
if( tex != null )
texturesNotToDestroy.Add( tex.name );
}
if( tex != null )
{
textures.Add( Path.GetFileName( f ), tex );
containedImages.Add( Path.GetFileName( f ) );
}
}
sheet.containedImages = containedImages.ToArray();
// pack all the textures and make a lookup dictionary
var textureArray = textures.Select( x => x.Value ).ToArray();
var rects = SKTextureUtil.rebuildAtlas( textureArray, sheet.name.Replace( "_sheet", string.Empty ) + "_atlas", sheet.hasHdAtlas );
var texToRect = new Dictionary<string,Rect>( textures.Count );
for( var i = 0; i < textureArray.Length; i++ )
{
var key = textures.Where( y => y.Value == textureArray[i] ).Select( x => x.Key ).First();
texToRect[key] = rects[i];
}
// create our textureInfos
foreach( var item in texToRect )
{
var tex = textures[item.Key];
var info = new SKTextureInfo();
info.file = item.Key;
info.uvRect = item.Value;
info.size = new Vector2( tex.width, tex.height );
textureInfoList.Add( info );
}
// clean up textures
foreach( var tex in textures )
{
// only destroy textures that we loaded from pngs
if( !texturesNotToDestroy.Contains( tex.Value.name ) )
GameObject.DestroyImmediate( tex.Value, true );
}
textures.Clear();
// not sure why getting the asset path triggers a save but it does for some reason
AssetDatabase.GetAssetPath( sheet );
sheet.imageTextureInfo = textureInfoList.ToArray();
//AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
EditorUtility.SetDirty( sheet );
}
catch( System.Exception e )
{
Debug.LogError( "Something went wrong creating the atlas: " + e );
}
finally
{
EditorUtility.ClearProgressBar();
isCurrentlyRefreshingSourceImages = false;
}
}