As I explore the 2D features of Unity, I discover more and more cool things. This time it was how to do animated sprites, but not just any animated sprites, sprites with multiple animations. We’ll cover the basics and a few pitfalls and shortcomings of this new technology.
UPDATE: Added missing step as noted in comments.
NOTE: Be sure to read the follow-up article :
Getting Started
First we need some artwork, I am generally a huge fan of opengameart.org so we’ll use some artwork from there today. This particular spritesheet was done as part of the “Liberated Pixel Cup” on opengameart.org, the artist is Skyler Robert Colladay, with the entry, FeralFantom's Entry.
Lets start a new Unity 2D project:
Open Unity 4.3 and select File->New Project. Lets name the project 2DAnimation and make sure you select 2D from the ‘Setup defaults for:’ drop down.
This will make Unity use a default working mode for 2D instead of 3D, but it’s easy enough to switch back and forth, don’t worry if you missed it the first time.
Since we aren’t creating a full game here I won’t go through the process of setting up all my asset folders, instead let’s just download the professor from above and add him to the asset folder.
- Right-Click the image and select ‘Save image as…’ or ‘Save picture as…’, then save the image in a folder.
- In Unity, Right-Click the Assets folder in the Project toolpane and select ‘Import New Asset…’
- In the ‘Import Asset’ dialog box, navigate to the folder where you saved the image from above, select the image and click the ‘Import’ button to import it into your new project.
Go ahead and rename the asset to just “professor_walk” it will be easier to work with in a bit.
Creating Sprites from a SpriteSheet
The next step is to divide this sheet into individual sprites. Unity has included a few new tools to make this happen a lot easier than it was previously. First, select your asset and look in the ‘Inspector’ toolpane.
Notice that the ‘Texture Type’ has been preset to Sprite. There are a lot of interesting knobs and switches on this panel, but for now we are only interested in the ‘Texture Type’ and ‘Sprite Mode’ options.
The default for ‘Sprite Mode’ is Single, which is not good for a sprite sheet. So let’s change that option to ‘multiple’, shall we?
The dialog changes a bit once we switch to ‘Multiple’ mode for a sprite. There are now fewer switches to play with, however, there is a very interesting new button that has piqued our interest. If you click the ‘Sprite Editor’ button, we can go satisfy that itch.
The ‘Sprite Editor’ as well as the ‘Sprite Texture Type’ are new to Unity 4.3. The new texture type importer allows us to manipulate the image in new and entertaining ways, specifically meant for 2D, while the editor allows us to fine tune how this sprite sheet is broken down into individual sprites.
Since this tool is new lets take a quick look at it’s features. We’ll start at the right an move to the left.
- This is the zoom tool, drag it left or right to quickly zoom in or out.
- This will toggle you between RGB mode and Alpha mode.
- These two buttons will either save you selections or cancel them.
- This is the real doozy of a tool, this will allow you to splice your sprite sheet into individual sprites.
There are three modes for the sprite editor, ‘Automatic’ and ‘Grid’ and Manual. ‘Automatic’ is for when you have sprites that are of different sizes spread out over the entire sheet. ‘Automatic’ will find the edges of the sprites and crop each sprite to a minimum size saving space. This generally does not work for animated sprites. Animated sprites will usually be the same size and arranged uniformly on the sheet. For those types of spritesheets, ‘Grid’ is the option you will want to use. The manual mode allows you the freedom to use the mouse and individually select the region for each sprite. This way the editor gives the most flexibility so that it can be used for just about every spritesheet imaginable.
Since our spritesheet is uniformly spaced, we can use the ‘Grid’ option to splice it up. The ‘Grid’ requires that you know the size for each sprite, and you enter that in the ‘X’ and ‘Y’ textboxes. Our spritesheet is 576px by 256px with sprites arranged in 4 animations (rows) with 9 frames (columns) each. When you do the math, it means that each sprite is 64px wide and 64px tall. How convenient! They are square, and those are the default values as well. If you had a spritesheet that wasn’t using 64x64px sprites, then you can just enter the correct values into the textboxes.
Finally, click the ‘Slice’ button to have the ‘Sprite Editor’ work it’s magic.
Voila! You can now see that the sprites have been sliced. Don’t worry, those lines you see won’t be in your actual sprites, they are added in the editor just so you know where each sprite is located. Now comes the real magic. Click the ‘Apply’ button, if you like what you have, otherwise click ‘Revert’ and try again. Once you are satisfied with your sprites, close the ‘Sprite Editor’.
Notice the little right arrow on the image in the ‘Assets’ window? Click that now to see how the ‘Sprite Editor’ has transformed your spritesheet into individual sprites, each on now has an asset name as well. Well now use these individual sprites to create the four animations.
Creating Animations
To get started select the first 9 sprites, which will make up our professor_walk_north animation.
Once you have them all selected, drag them onto the scene. Unity will prompt you to save the animation, so lets give it a name of “professor_walk_north”.
At the same time, Unity will create a Controller and a ‘GameObject’ in the scene, we’ll come back to those in a second. For now, repeat this process for the next 3 sets of nine, and name them “professor_walk_east”, “professor_walk_south” and “professor_walk_south” respectively. Once you have completed that, switch to the ‘Game’ tab, and run the scene.
What you should see are all four of your game objects in motion. If you don’t delete them all and start over again.
Now stop the game and flip back to the scene tab before you continue.
If you select one of the GameObjects in the scene, the ‘Inspector’ toolpane will show you the components that are assigned to this GameObject. Notice the last one is ‘Animator’ and in my case it’s ‘Controller’ property is set to the ‘professor_walk_18’ object. The Animator Component provides a connection from your GameObject to the AnimationController so that as things change in your game, the AnimationController can adapt and provide those changes to the GameObject.
The way the Animation Controller works, is that it is simply a state machine. When you first create an animation it creates a Controller with one state in it. This state is hooked up to your animation.
The GameObject (bone) is connected to the…Animator (bone).
The Animator (bone) is connected to the…Controller (bone).
The Controller (bone) is connected to the…Motion (bone).
The Motion (bone) is connected to the…Sprite (bone).
But Wait, There’s More! We are not done yet. While you could stop here and use the four GameObjects, wouldn’t it be easier if this was all combined into a single GameObject and Controller? You betcha it would be, and that’s what’s next.
I am going to pick the professor facing me as my GameObject. I’ll delete the other 3 GameObjects from the scene and rename the remaining one to be just ‘professor’. Deleting the GameObjects doesn’t delete the associated Animator Controller or Animation objects, which is good for us.
Let’s remove the extra Animator Controllers as well. Make sure you don’t delete the Controller that is currently connected to the ‘GameObject’. To see which on it is, click the Controller name in the ‘Inspector’ toolpane. Once you’ve removed the extra ones, rename the remaining one to ‘professorAnimatorController’. Once you are done, you should have a GameObject, one Animation Controller and 4 animations.
Let’s open the ‘professorAnimationController’ to hook up the other three animations. As I mentioned previously the Animation Controller is a state machine. Each state represents an animation. Transitions are used to allow the controller to move the current state to a new state.
To add new states for our other three directions, Right-Click in the designer, select ‘Create State’->’Empty’ and use the inspector to rename the states.
Now, to create the transitions, Right-Click the state and select ‘Make Transition’, then click on the state to transition to.
Do this for each state to the other 3 states.
To associate each animation to the state, drag the animation from the ‘Assets’ toolpane to the ‘Inspector’ toolpane and drop it on the ‘Motion’ property.
To make each transition ‘fire’ when appropriate we need to create a parameter that will change it’s value. Each transition will have a condition that will test the value of the parameter and if it’s true, the transition will occur and the state will change, causing the animation to change as well.
Let’s create the parameter for the Animation Controller. In the lower left hand corner of the designer is a small pane titled ‘Parameters’. Click the ‘+’ at the right hand side of that pane to create a new parameter.
Select ‘Int’ from the list of available parameter types, and name the parameter ‘Direction’.
Now there is a way to control when the transitions will cause a change of state. The following table specifies the rules we will use to dictate what the values of the parameter mean.
Value | State |
0 | South |
1 | West |
2 | North |
3 | East |
To configure the transitions correctly, select each state, then in the ‘Inspector’ toolpane select each transition. Once you select a transition more knobs and switches show up, but what we are interested in is under the heading ‘Conditions’ The default is to use the ‘Exit Time’, but since we have a control parameter we’ll use that. Hit the drop down and select ‘Direction’ from the list.
So if I’m editing the south state, and the south->east transition, then I want the condition to be ‘Direction equals 3’. The south to north transition would be ‘Direction equals 2’ and so on. Go ahead and finish setting up the remainder of the transitions and we’ll wrap up in a moment.
Finishing Touches
Before we wrap this all up in a nice red bow for you, run the game again. Your professor should be walking toward you. Then switch tabs back to the ‘Animator’ tab and change the value of the ‘Direction’ parameter to 1,2 or 3. Now switch back to the ‘Game’ tab and see that the professor is now walking in a different direction.
To wrap this up, lets hook the arrow keys to each direction, instead of manually changing the ‘Direction’ Parameter.
Start by adding a new C# script to the assets folder. Right-Click in the Assets toolpane and select Create->C#Script. Name the new asset “playerController”.
Double-Click the ‘playerController’ script to open the file in either MonoDevelop, or Visual Studio, depending on your preferences, mine are for Visual Studio 2013, and I’ll show you how to set that in another post.
Copy and paste the following code into the script file, save it, then switch back to Unity.
public class playerController : MonoBehaviour { private Animator animator; // Use this for initialization void Start() { animator = this.GetComponent<Animator>(); } // Update is called once per frame void Update() { var vertical = Input.GetAxis("Vertical"); var horizontal = Input.GetAxis("Horizontal"); if (vertical > 0) { animator.SetInteger("Direction", 2); } else if (vertical < 0) { animator.SetInteger("Direction", 0); } else if (horizontal > 0) { animator.SetInteger("Direction", 1); } else if (horizontal < 0) { animator.SetInteger("Direction", 3); } } }
Now, drag the ‘playerController’ script from the Assets toolpane onto your ‘professor’ GameObject node in the hierarchy toolpane to attach the controller to the GameObject.
Finally, test out your game one last time.
You should be able to change the animation of the professor using the arrow keys on the keyboard.
Wrap Up
Today we explored how to leverage the new built in capabilities of Unity 4.3 to use sprite sheets for 2d animation. The majority of the effort was in configuration and setup, with almost no writing of code. This means that there will be a smaller chance that you introduce a bug into your game. We discovered that having multiple animations involves a bit more effort, but in the end, it’s much more manageable then what was in previous versions of Unity.