Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Animate Spritesheets in a Unity 2D Game

TwitterFacebookRedditLinkedInHacker News

When it comes to developing a game, at some point in time you’re going to want to animate some component within the game. These animations could be character sprites or even elements that exist as part of the background.

A few months back, I wrote a tutorial titled, Animate Spritesheets in a Phaser Game, around creating a spritesheet and then animating it within a Phaser game. Phaser is an awesome framework, but it doesn’t compare to Unity on a professional level. So what if we wanted to animate a spritesheet in Unity?

In this tutorial we’re going to see how to animate a spritesheet, the same example from the previous tutorial, but this time with Unity, animation clips, animator states, and some basic C#.

To get an idea of what we want to accomplish, take a look at the following animated image:

Unity Spritesheet Animation Example

In the above animated image we have a plane with wind streaks to give the illusion that it is flying. After a certain amount of time or event, the plane disappears and an explosion-like animation plays before the entire sprite disappears from the screen. Both animations are part of the same spritesheet and the same game object within Unity.

Create a New Unity Project with the 2D Template

Before we get to the core material, it makes sense to start with a fresh Unity project. Within the Unity Hub, create a new project using the 2D template.

Unity New 2D Project

I’m going to skip a few steps in terms of image instructions, but you’re going to want to create an Animations, Scripts, and Textures directory within the project assets. You’re also going to want to create an empty game object within the scene.

Your project should look something like the following:

Unity 2D Project with Boilerplate

Even though we have a project with a game object, we’re not actually rendering anything to the screen. The game object is not technically a sprite and it has no animations associated to it.

Packing Spritesheets and Defining Animation Clips with Unity

To animate something in 2D, we’re going to need multiple frames to iterate over. This means we’re going to need a new image for each frame in our animation. The more unique images, the smoother the animation will appear because there will be more unique frames.

In Unity we could create, say ten images, and add each image into the project. The problem with this is that loading individual images is resource intensive and inappropriate for a game that is dependent on performance. For this reason, tiling each frame into a single image, otherwise known as a spritesheet, is a better option.

There are numerous ways to handle a spritesheet, but the simplest is to use a spritesheet where each sprite is exactly the same size as the other sprites. Sure it won’t be an optimized spritesheet, but it will be easy and better than nothing.

Take the following spritesheet for example:

Plane Spritesheet

The above spritesheet was created with a software called TexturePacker. You don’t need TexturePacker to create spritesheets, but it makes life significantly easier. The alternative is taking each of your sprite images and building a spritesheet manually with a tool like Adobe Photoshop.

Go ahead and download my spritesheet and add it to the Textures directory within the Unity project.

Within Unity, we need to define what exactly the image file is. This means defining each image in the spritesheet as well as the pixels per unit.

Define Sprites within Spritesheet in Unity

After selecting the image, change the Sprite Mode to Multiple and then select the Sprite Editor from the inspector. Within the Sprite Editor choose to create a grid based on the cell size. We know that each sprite within the spritesheet is 512x512, so defining this in the Sprite Editor will allow unity to access each sprite separately, whenever we want.

With the spritesheet properly referenced within Unity, click on the game object, and then choose Window -> Animation -> Animation from the menu.

Show Unity Animation Window

The Animation window is where we’re going to define each of our possible animation clips. Our example is going to have two animations, one for the plane flying and one for the plane exploding.

Within the Animation window, create a new animation titled, Flying, and save it to the Animations directory within the project assets. Create another animation titled, Exploding, and save it to the same directory.

Unity Animation Clip

Select one of the two new animation clips within the Animation window and drag the relevant sprites from the spritesheet into the window. These sprites will animate for that particular clip. Depending on how many sprites you have, you may need to lower the Samples field. In our example, seven is a good number to work with.

The animations are defined, but we need to be able to determine when they should play. This is where the animator comes into the scenario.

Managing Animation Clips with States in a Unity Animator Controller

The Unity Animator is where we define each of our animation states and how to transition between them. In our example, we’d transition to flying, and then from flying to exploding, but probably never exploding from another state.

Choose Window -> Animation -> Animator from the menu.

Open Unity Animator Window

You should be presented with a window that has a few states, two of which are named after the animation clips that we had created prior. You’ll also notice an Any State, Entry, and Exit state that come as part of the animator state lifecycle.

Unity Animator Transitions

The goal here is to define transitions between the states. For example, the Entry state leads to the default animation, which should be Flying in our example. The Any State state leads to where we can transition to on-demand. It’s probably not likely that we will want to transition from anywhere to the Exploding state.

If you click on any of the transitions, you can define conditions. However, before we can define conditions we need to declare possible parameters. Create two trigger parameters. The goal is to use these triggers as conditions when they enter the true state. The state of these triggers will eventually be defined in a C# script.

If you were to run your game right now, the plane would be animated as if it were flying. It will not explode and it will not disappear. It will only fly forever.

Changing the Unity Animation State for a Sprite in a C# Script

We have our possible animations and we have a state controller defined. Now we need to trigger state events from a C# script.

Create a Plane.cs script within the Scripts directory. This script should be added as a component on the game object that is representing our plane. By default the script should look like the following:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Plane : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

Since collisions and other realistic events are out of the scope of this particular example, we’re going to change the animation based on a timer. However, you can easily change things based on your needs.

Within the Plane.cs file, change it to look like the following:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Plane : MonoBehaviour
{

    private Animator animator;

    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();

        StartCoroutine(ExplodeCoroutine());
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    IEnumerator ExplodeCoroutine()
    {
        yield return new WaitForSeconds(3);
        animator.SetTrigger("Explode");
        Destroy(gameObject, 1.5f);
    }
}

In the above code we are obtaining the animator that exists on our game object. Remember, this is the animator that has our two animations and all the states with transitions.

In the Start method we start a coroutine. In that coroutine we wait for three seconds before setting the trigger that transitions from the Flying animation to our Exploding animation. Since we don’t want to explode forever, we configure the game object to be destroyed after ninety seconds.

Give it a try! The plane should fly for a few seconds and then explode. Finally the plane and explosion should disappear because the game object was destroyed.

Conclusion

This tutorial went over a few different topics that brought us to animating a spritesheet. The goal was to take a single image spritesheet that contained several sprite images and animate them as frames. We took that spritesheet, parsed it in Unity, defined two different animations, and then controlled those animations with an animator and a script with logic.

Spritesheets can be optimized beyond what we saw in this tutorial and they can contain more sprites than what we used. However, spritesheets should definitely be used and they are quite easy to animate since most of what we did was point and click with configurations in Unity.

This tutorial was based on an example I had done with Phaser titled, Animate Spritesheets in a Phaser Game.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.