-
-
Save unitycoder/9f10f25646fd22356987c8631e0cbd90 to your computer and use it in GitHub Desktop.
UNITY sprite auto slicer. Put into any Editor/ directory. Use it in combination with Presets/PresetManager for importer settings.
This file contains hidden or 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 System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using UnityEditor; | |
using UnityEditorInternal; | |
using UnityEngine; | |
public class AutoSpriteSlicer : AssetPostprocessor | |
{ | |
private const string PathTrigger = "_AnimationSheet"; | |
private const char FileNameSeparator = '_'; | |
private const char SizeSeparator = 'x'; | |
private static string _processedFile; | |
private void OnPostprocessTexture(Texture2D texture) | |
{ | |
if (!assetPath.Contains(PathTrigger)) return; | |
if (_processedFile != null) | |
{ | |
_processedFile = null; | |
return; | |
} | |
_processedFile = assetPath; | |
TextureImporter textureImporter = (TextureImporter)assetImporter; | |
string fileName = Path.GetFileNameWithoutExtension(assetPath); | |
string[] rectangleSize = fileName.Split(FileNameSeparator).Last().Split(SizeSeparator); | |
if (rectangleSize.Length < 2) return; | |
Vector2 spriteBoxSize = new Vector2(int.Parse(rectangleSize[0]), int.Parse(rectangleSize[1])); | |
Rect[] rectangles = InternalSpriteUtility.GenerateGridSpriteRectangles( | |
texture, | |
Vector2.zero, | |
spriteBoxSize, | |
Vector2.zero, | |
true | |
); | |
int rectNum = 0; | |
textureImporter.spritesheet = rectangles.Select(rect => new SpriteMetaData | |
{ | |
pivot = Vector2.down, | |
alignment = (int) SpriteAlignment.BottomCenter, | |
rect = rect, | |
name = fileName + "_" + rectNum++ | |
}).ToArray(); | |
AssetDatabase.ForceReserializeAssets(new List<string> { assetPath }); | |
AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment