Skip to content

Instantly share code, notes, and snippets.

@SiarheiPilat
Created June 12, 2020 21:48
Show Gist options
  • Save SiarheiPilat/c2772d2fcedf70b97e0f88fdad2e5b27 to your computer and use it in GitHub Desktop.
Save SiarheiPilat/c2772d2fcedf70b97e0f88fdad2e5b27 to your computer and use it in GitHub Desktop.
Simple editor script that allows to set pivot for multiple slices of a sprite sheet automatically, so you won't have to do it manually. The sprite sheet has to be sliced beforehand.
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(SpritesheetPivotEditor))]
public class SpritesheetPivotEditor : EditorWindow
{
[MenuItem("Tools/Sprites/Pivot Editor")]
static void OpenPivotEditor()
{
SpritesheetPivotEditor window = (SpritesheetPivotEditor)GetWindow(typeof(SpritesheetPivotEditor));
window.minSize = new Vector2(300, 300);
window.Show();
}
private void OnGUI()
{
EditorGUILayout.LabelField("Select the sprite sheet first");
if (GUILayout.Button("Top Left"))
{
SetPivots(1);
}
if (GUILayout.Button("Top Center"))
{
SetPivots(2);
}
if (GUILayout.Button("Top Right"))
{
SetPivots(3);
}
if (GUILayout.Button("Left Center"))
{
SetPivots(4);
}
if (GUILayout.Button("Center"))
{
SetPivots(0);
}
if (GUILayout.Button("Right Center"))
{
SetPivots(5);
}
if (GUILayout.Button("Bottom Left"))
{
SetPivots(6);
}
if (GUILayout.Button("Bottom Center"))
{
SetPivots(7);
}
if (GUILayout.Button("Bottom Right"))
{
SetPivots(8);
}
}
// Pivot alignment:
//
// +----------------+------------------+-----------------+
// | TopLeft = 1 | TopCenter = 2 | TopRight = 3 |
// +----------------+------------------+-----------------+
// | LeftCenter = 4 | Center = 0 | RightCenter = 5 |
// +----------------+------------------+-----------------+
// | BottomLeft = 6 | BottomCenter = 7 | BottomRight = 8 |
// +----------------+------------------+-----------------+
// +---------------+
// | Custom = 9 |
// +---------------+
static void SetPivots(int Alignment)
{
Object[] textures = Selection.GetFiltered(typeof(Texture2D), SelectionMode.DeepAssets);
Selection.objects = new Object[0];
foreach (Texture2D texture in textures)
{
string path = AssetDatabase.GetAssetPath(texture);
TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter;
ti.isReadable = true;
List<SpriteMetaData> newData = new List<SpriteMetaData>();
for (int i = 0; i < ti.spritesheet.Length; i++)
{
SpriteMetaData d = ti.spritesheet[i];
d.alignment = Alignment;
newData.Add(d);
}
ti.spritesheet = newData.ToArray();
ti.isReadable = false;
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
ti.isReadable = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment