- Home /
Batch operation to slice sprites in editor?
Using unity 5.3.0 f4 - Win 7 64
I am trying to speed up the process of importing little sprites and slicing them in batches by script. So I started hunting around for a method to do that, and found this question and answer:
http://answers.unity3d.com/questions/943797/editor-script-to-slice-sprites.html
Where a script is shared that is supposed to do that - slice up a sprite through an editorscript.
Anyway I edited it a bit to deal with a pile of sprites loaded from the resources folder and then go through the operation 125 times (because I have 125 total sprites for this test). Here is what I tried (must be in the editor folder to work, you select EditorHelper > SliceSprites at the top):
working code in answer!
And this does nothing. It slows down the editor and loads for a minute like it could be working, but for some reason when it is done, the files seem to be unchanged. No slices, still set to single sprite mode, nothing any different. What gives? Is unity 5.3 not liking this code for some reason? Is there a problem writing back the changes? Anybody have a working solution to a problem like this?
Answer by MD_Reptile · Dec 15, 2015 at 10:45 PM
I got it working, I guess it didn't matter in past unity versions since that worked in the first answer for those guys, but I had to set the sprite mode to multiple before it would work! Here is the working script:
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
public class EditorHelper : MonoBehaviour
{
private static int totalSprites = 125; // change depending on the total sprites in this batch!
[MenuItem("EditorHelper/SliceSprites")]
static void SliceSprites()
{
Texture2D[] textures = new Texture2D[totalSprites];
for (int z = 0; z < totalSprites; z++)
{
// path is Assets/Resources/Sprites/Sprite (1).png
textures[z] = Resources.Load<Texture2D>("Sprites/Sprite (" + (z + 1) + ")");
string path = AssetDatabase.GetAssetPath(textures[z]);
TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter;
ti.isReadable = true;
ti.spriteImportMode = SpriteImportMode.Multiple;
List<SpriteMetaData> newData = new List<SpriteMetaData>();
int SliceWidth = 12;
int SliceHeight = 12;
for (int i = 0; i < textures[z].width; i += SliceWidth)
{
for (int j = textures[z].height; j > 0; j -= SliceHeight)
{
SpriteMetaData smd = new SpriteMetaData();
smd.pivot = new Vector2(0.5f, 0.5f);
smd.alignment = 9;
smd.name = (textures[z].height - j) / SliceHeight + ", " + i / SliceWidth;
smd.rect = new Rect(i, j - SliceHeight, SliceWidth, SliceHeight);
newData.Add(smd);
}
}
ti.spritesheet = newData.ToArray();
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
}
Debug.Log("Done Slicing!");
}
}
You're awesome, thank you. I'm working on a game where I have several spritesheets with 70+ subsprites and before this I had to rename them all by hand. You probably saved me hours of work. :)
I made a quick change this this script to just do all of the selected texture2ds.
[$$anonymous$$enuItem("EditorHelper/SliceSpritesVV")] static void SliceSpritesVV() { Texture2D[] textures = new Texture2D[totalSprites]; foreach(var si in Selection.objects ) { // path is Assets/Resources/Sprites/Sprite (1).png var tex = si as Texture2D; string path = AssetDatabase.GetAssetPath(tex); TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter; ti.isReadable = true; ti.spriteImport$$anonymous$$ode = SpriteImport$$anonymous$$ode.$$anonymous$$ultiple; List<Sprite$$anonymous$$etaData> newData = new List<Sprite$$anonymous$$etaData>(); int SliceWidth = 48; int SliceHeight = 48; for (int i = 0; i < tex.width; i += SliceWidth) { for (int j = tex.height; j > 0; j -= SliceHeight) { Sprite$$anonymous$$etaData smd = new Sprite$$anonymous$$etaData(); smd.pivot = new Vector2(0.5f, 0.5f); smd.alignment = 9; smd.name = (tex.height - j) / SliceHeight + ", " + i / SliceWidth; smd.rect = new Rect(i, j - SliceHeight, SliceWidth, SliceHeight); newData.Add(smd); } } ti.spritesheet = newData.ToArray(); AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate); } Debug.Log("Done Slicing!"); }
Answer by ChloeOfArroyo · Jan 23, 2020 at 08:20 AM
As an update to this script (many thanks to @MD_Reptile for sharing!) I have tweaked this script to make it slice any Texture2D placed within a folder in 'Assets/Resources' called 'ToSlice'. You no longer need the sprites to have a specific naming scheme, or specify the number of sprite sheets - it will do them all.
You can have it look in another folder of your choice if you change the 'folderPath' variable, as long as it is in the 'Resources' Folder. using System.Collections; using UnityEditor; using System.Collections.Generic; using UnityEngine;
public class EditorHelper : MonoBehaviour
{
[MenuItem("EditorHelper/SliceSprites")]
static void SliceSprites()
{
// Change the below for the with and height dimensions of each sprite within the spritesheets
int sliceWidth = 32;
int sliceHeight = 32;
// Change the below for the path to the folder containing the sprite sheets (warning: not tested on folders containing anything other than just spritesheets!)
// Ensure the folder is within 'Assets/Resources/' (the below example folder's full path within the project is 'Assets/Resources/ToSlice')
string folderPath = "ToSlice";
Object[] spriteSheets = Resources.LoadAll(folderPath, typeof(Texture2D));
Debug.Log("spriteSheets.Length: " + spriteSheets.Length);
for (int z = 0; z < spriteSheets.Length; z++)
{
Debug.Log("z: " + z + " spriteSheets[z]: " + spriteSheets[z]);
string path = AssetDatabase.GetAssetPath(spriteSheets[z]);
TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter;
ti.isReadable = true;
ti.spriteImportMode = SpriteImportMode.Multiple;
List<SpriteMetaData> newData = new List<SpriteMetaData>();
Texture2D spriteSheet = spriteSheets[z] as Texture2D;
for (int i = 0; i < spriteSheet.width; i += sliceWidth)
{
for (int j = spriteSheet.height; j > 0; j -= sliceHeight)
{
SpriteMetaData smd = new SpriteMetaData();
smd.pivot = new Vector2(0.5f, 0.5f);
smd.alignment = 9;
smd.name = (spriteSheet.height - j) / sliceHeight + ", " + i / sliceWidth;
smd.rect = new Rect(i, j - sliceHeight, sliceWidth, sliceHeight);
newData.Add(smd);
}
}
ti.spritesheet = newData.ToArray();
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
}
Debug.Log("Done Slicing!");
}
}
Answer by Wedoe · Nov 28, 2019 at 09:10 AM
Hi, am looking to implement this into my current project, but somehow this line is giving me a NullReferenceException: Object reference not set to an instance of an object
ti.isReadable = true;
I've been trying my best to figure out why, tried moving sprites around in the Asset folders. Tried renaming. But everytime it's the same.
Answer by blisz · Oct 15, 2021 at 04:35 PM
Hey,
Thank you for the script, it works well. :) Any ideas how to make it not keep the empty rects? @ChloeOfArroyo
Answer by FreeReignPublishing · Feb 05 at 07:08 AM
here's an overhaul to the script...
Added a seperate window under the menu item for slicing
Can now auto slice a sprite ie "can cut out nothing but the sprite from dead space"
To slice a sprite select one or more in the asset hierarchy then click the slice button in the window
Can change the pivot for each sprite sliced
Can change the threshold ie "the max pixel opacity to check for when auto slicing"
Make sure to put this script in a folder called: Editor
using UnityEditor;
using System.Collections.Generic;
using UnityEngine;
public class SpriteSlicer : EditorWindow
{
static float threshold = 1;
static Vector2 pivot = new Vector2(0.5f, 0.5f);
void OnGUI()
{
threshold = Mathf.Clamp(EditorGUILayout.FloatField("Threshold: ", threshold), 0, 1);
pivot = EditorGUILayout.Vector2Field("Pivot: ", pivot);
if (GUILayout.Button("Slice"))
{
Slice();
}
this.Repaint();
}
[MenuItem("Sprite Slicer/Open Slicer")]
static void OpenSlicer()
{
EditorWindow.GetWindow(typeof(SpriteSlicer));
}
static void Slice()
{
Object[] spriteSheets = Selection.GetFiltered<Texture2D>(SelectionMode.Assets);
for (int z = 0; z < spriteSheets.Length; z++)
{
string path = AssetDatabase.GetAssetPath(spriteSheets[z]);
TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter;
ti.isReadable = true;
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
if (ti.spriteImportMode != SpriteImportMode.Single)
ti.spriteImportMode = SpriteImportMode.Single;
ti.spriteImportMode = SpriteImportMode.Multiple;
List<SpriteMetaData> newData = new List<SpriteMetaData>();
Texture2D spriteSheet = spriteSheets[z] as Texture2D;
int maxY = 0;
int maxX = 0;
int minY = spriteSheet.height;
int minX = spriteSheet.width;
for (int i = 0; i < spriteSheet.width; i++)
{
for (int j = spriteSheet.height; j >= 0; j--)
{
if (spriteSheet.GetPixel(i, j).a >= threshold && j > maxY)
maxY = j;
if (spriteSheet.GetPixel(i, j).a >= threshold && j < minY)
minY = j;
if (spriteSheet.GetPixel(i, j).a >= threshold && i > maxX)
maxX = i;
if (spriteSheet.GetPixel(i, j).a >= threshold && i < minX)
minX = i;
}
}
SpriteMetaData smd = new SpriteMetaData();
smd.pivot = pivot;
smd.alignment = 9;
smd.name = spriteSheet.name;
smd.rect = new Rect(minX, minY, (maxX - minX) + 1, (maxY - minY) + 1);
newData.Add(smd);
ti.spritesheet = newData.ToArray();
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
}
}
}