Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by MD_Reptile · Dec 15, 2015 at 09:44 PM · spriteeditorscriptsliceslicingbatch

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?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

5 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

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!");
     }
 }
Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image aleichert · Mar 31, 2016 at 01:11 AM 0
Share

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. :)

avatar image MD_Reptile · Mar 31, 2016 at 02:10 AM 0
Share

No problem, glad I could help!

avatar image Zelxin · Jul 07, 2019 at 11:28 PM 0
Share

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!"); }

avatar image
1

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!");
     }
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Wedoe · Nov 28, 2019 at 09:10 AM

@MD_Reptile

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.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

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

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

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);
         }
     }
 }











Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

40 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Using pre-sliced Unity Asset? 1 Answer

sliced sprite taking part of one above it 1 Answer

How UI Batching works with two different sprites ? 0 Answers

How to slice a sprite realime C# 3 Answers

Mesh slicing or shattering 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges