Currently I am working on a 2D game in Unity. I am working on a EditorWindow to slice an imported spritesheet and create animations from these sprites.
Currently, I have the code to slice the spreadsheet functioning, detailed below for those interested in referencing:
public void Slice()
{
var textures = Selection.GetFiltered<Texture2D>(SelectionMode.Assets);
foreach (var texture in textures)
{
ProcessTexture(texture, pixelPerUnit, spriteSize, pivot, alignment);
}
}
static void ProcessTexture(Texture2D texture, int pixelPerUnit,
Vector2Int spriteSize, Vector2 pivot, Alignment alignment)
{
string path = AssetDatabase.GetAssetPath(texture);
{
TextureImporter textureImporter =
TextureImporter.GetAtPath(path) as TextureImporter;
//Set characteristics for spritesheet
textureImporter.textureType = TextureImporterType.Sprite;
textureImporter.spriteImportMode = SpriteImportMode.Multiple;
textureImporter.spritePixelsPerUnit = pixelPerUnit;
textureImporter.filterMode = FilterMode.Point;
textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
int colCount = texture.width / spriteSize.x;
int rowCount = texture.height / spriteSize.y;
//Create Spritesheet Metadata based on characteristics
List<SpriteMetaData> metas = new List<SpriteMetaData>();
for (int c = 0; c < colCount; c++)
{
for (int r = 0; r < rowCount; r++)
{
SpriteMetaData meta = new SpriteMetaData();
meta.rect = new Rect(c * spriteSize.x,
r * spriteSize.y,
spriteSize.x, spriteSize.y);
meta.name = (rowCount - r - 1) + "-" + c;
meta.alignment = (int)alignment;
meta.pivot = pivot;
metas.Add(meta);
}
}
//Apply the metadata to the spritesheet
textureImporter.spritesheet = metas.ToArray();
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
}
}
The portion that is currently giving me grief is converting this newly sliced spreadsheet into animations through script.
Currently I can create an empty animation clip in the directory of the spritesheet using the code snippet below:
string path = AssetDatabase.GetAssetPath(texture);
string newPath = Path.GetDirectoryName(path);
AnimationClip clip = new AnimationClip();
AssetDatabase.CreateAsset(clip, newPath + "\\" + spriteName ".anim");
I am having difficulty finding out how to add sprites to this newly created animation. I have looked into AnimationCurves and AnimationEvents but I cannot seem to find the step to link a sprite to the animation through the editor.
If anyone has experience or knowledge regarding the creation of unity animationclips through script, any insight would be greatly appreciated. If any more information is needed on my end, please let me know. This is my first time using this service. Thank you all for your help!