Unity component for easily defining and playing 2D sprite animations in script
Alternative Workflow for Creating and Playing Animations
Placing sprites frame by frame in an animation clip in Unity is tedious, finicky, and brittle. And then after you make an animation clip you still have to arrange them in mecanim, which auto-generates transition animations (for blended animations so useful for 3D), which you then have to manually remove. If it sounds only kind of annoying, I promise you I undersold it. I remember the good old days of Flixel where you could play an animation from a sprite sheet in just three lines of code
So how to get something as simple as the above Flixel snippet? First, add the RetroSpriteAnimator component to the same game object you want to animate. Then simply drag the (hopefull already sliced) sprite-sheet to the 'Sprite' field.
If you'd rather define the sprite via could, you can call the CreateSprite method instead.
The first parameter is just the asset path to the sprite-sheet (remember, in order to load assets via code, Unity requires that all assets are placed within the /Assets/Resources directory, so the full asset path in this examples is ".../Assets/Resources/Sprites/16/frog.png"). The optional second parameter is Unity layer you want the asset to be associated with.
So now Unity has a reference to this sprite sheet:
Next we need to define an animation to play. We can do this using the AddAnimation method.
In the first parameter, name the animation something. Probably something descriptive and unique. The second parameter defines which animations to use. So with an array of 0, 1, 1, 2, I'm having the game play the first frame, the second frame twice, and then the last frame once (at a frame rate of 7 frames per second, which is what I set agentFrameRate to by the way).
The last two parameters choose whether the animation loops (we're making a walking animation, so yes), and if the animation should be flipped horizontally (in frog.png the frog is facing right, but we're making an animation that's walking left, so that's a yes). Now we just play the animation.
With any luck we'll end up with something like this:
Again, feel free to grab RetroSpriteAnimator on GitHub, and let me know what you think!
Shoutout to Adam Saltsman (@ADAMATOMIC), whose open-source Flixel more than inspired RetroSpriteAnimator, and to Luis Zuno (@ansimuz) for his adorably rad Creative Commons art.