Skip to content

Instantly share code, notes, and snippets.

@edwardrowe
Last active February 3, 2023 06:42
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edwardrowe/507d1f49221b6947f532 to your computer and use it in GitHub Desktop.
Save edwardrowe/507d1f49221b6947f532 to your computer and use it in GitHub Desktop.
Unity - Build Clip From Selected Texture
/*The MIT License (MIT)
Copyright (c) 2016 Edward Rowe (@edwardlrowe)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
public static class AnimClipBuilder
{
public static AnimationClip CreateClip(Sprite[] sprites, string clipName)
{
// Output nothing if there is no clip name
if (string.IsNullOrEmpty(clipName))
{
return null;
}
// Could be inputs
int sampleRate = 12;
bool isLooping = false;
// Create a new Clip
AnimationClip clip = new AnimationClip();
// Apply the name and framerate
clip.name = clipName;
clip.frameRate = sampleRate;
// Apply Looping Settings
AnimationClipSettings clipSettings = new AnimationClipSettings();
clipSettings.loopTime = isLooping;
AnimationUtility.SetAnimationClipSettings(clip, clipSettings);
// Initialize the curve property for the animation clip
EditorCurveBinding curveBinding = new EditorCurveBinding();
curveBinding.propertyName = "m_Sprite";
// Assumes user wants to apply the sprite property to the root element
curveBinding.path = "";
curveBinding.type = typeof(SpriteRenderer);
// Build keyframes for the property using the supplied Sprites
ObjectReferenceKeyframe[] keys = CreateKeysForSprites(sprites, sampleRate);
// Build the clip if valid
if (keys.Length > 0)
{
// Set the keyframes to the animation
AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keys);
}
return clip;
}
private static ObjectReferenceKeyframe[] CreateKeysForSprites(Sprite[] sprites, int samplesPerSecond)
{
List<ObjectReferenceKeyframe> keys = new List<ObjectReferenceKeyframe>();
float timePerFrame = 1.0f / samplesPerSecond;
float currentTime = 0.0f;
foreach (Sprite sprite in sprites)
{
ObjectReferenceKeyframe keyframe = new ObjectReferenceKeyframe();
keyframe.time = currentTime;
keyframe.value = sprite;
keys.Add(keyframe);
currentTime += timePerFrame;
}
return keys.ToArray();
}
}
/*The MIT License (MIT)
Copyright (c) 2016 Edward Rowe (@edwardlrowe)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class AnimClipBuilderTool
{
private const string MenuItemPath = "Assets/AnimationClipUtility/Create Clip from Sprites";
[MenuItem(MenuItemPath)]
public static void CreateAnimClip()
{
Texture2D selectedTexture = (Texture2D)Selection.activeObject;
Sprite[] sprites = GetSpritesFromTexture(selectedTexture);
string filename = selectedTexture.name + ".anim";
AnimationClip clip = AnimClipBuilder.CreateClip(sprites, filename);
string fullClipPath = GetSavePathFromTexture(selectedTexture, filename);
try
{
SaveClip(clip, fullClipPath, false);
}
catch (System.IO.IOException)
{
if (EditorUtility.DisplayDialog("Warning: File Exists",
"This will overwrite the existing clip, " + filename +
". Are you sure you want to create the clip?", "Yes", "No"))
{
SaveClip(clip, fullClipPath, true);
}
}
}
private static Sprite[] GetSpritesFromTexture(Texture2D texture)
{
string path = AssetDatabase.GetAssetPath(texture);
if (string.IsNullOrEmpty(path))
{
Debug.LogWarning("Can't find sprites from Texture at path: " + path);
return null;
}
// Load all the sprites from the texture path
// (Note, this does not load them in the order they appear in editor so they must be sorted)
Sprite[] spriteArray = AssetDatabase.LoadAllAssetsAtPath(path).OfType<Sprite>().ToArray();
// Sort the spritelist in editor order
List<Sprite> spriteList = new List<Sprite>(spriteArray);
spriteList.Sort(delegate(Sprite x, Sprite y)
{
return EditorUtility.NaturalCompare(x.name, y.name);
});
return spriteList.ToArray();
}
private static string GetSavePathFromTexture(Texture2D selectedTexture, string filename)
{
string texturePath = AssetDatabase.GetAssetPath(selectedTexture);
string textureDirectory = System.IO.Path.GetDirectoryName(texturePath) + System.IO.Path.DirectorySeparatorChar;
string fullClipPath = textureDirectory + filename;
return fullClipPath;
}
private static void SaveClip(AnimationClip clip, string path, bool allowOverride)
{
if (!allowOverride && System.IO.File.Exists(path))
{
throw new System.IO.IOException("Clip already exists at path");
}
else
{
AssetDatabase.CreateAsset(clip, path);
}
}
[MenuItem(MenuItemPath, true)]
private static bool ValidateSelection()
{
if (!IsSelectionValidTexture())
{
return false;
}
if (Selection.objects.Length > 1)
{
return false;
}
return true;
}
private static bool IsSelectionValidTexture()
{
if (Selection.activeObject == null)
{
return false;
}
return Selection.activeObject.GetType() == typeof(Texture2D);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment