Welcome back to our Unity 4.3 2D Tutorial series!
In the first part of the series, you started making a fun game called Zombie Conga. You learned how to add sprites, work with sprite sheets, configure the game view, and animate and move sprites using scripts.
In this second part of the series, you will re-animate the zombie (he is undead, after all), this time using Unity’s built-in animation system. You’ll also add several animations to the cat sprite.
By the time you’re done, you’ll have a great understanding of Unity’s powerful animation system, and Zombie Conga will get its groove on!
Getting Started
First download this starter project, which contains everything from the first installment in this tutorial series, Unity 4.3 2D Tutorial: Getting Started. If you really want to, you can continue with your old project, but it’s better to use this starter project so you’re sure to be in the right place.
Unzip the file and open your scene by double-clicking ZombieConga/Assets/Scenes/CongaScene.unity:
While these assets are the same as the ones you made in Unity 4.3 2D Tutorial: Getting Started, this version of the project has been organized into several folders: Animations, Scenes, Scripts and Sprites. This will help keep things tidy as you add assets to the project.
You’ll store the animations you create in this tutorial in the Animations folder; the other folders have names that clearly describe their contents.
Note: If your folders show up as icons rather than small folders, you can drag the slider in the bottom right of the window to change to the view you see here. I will switch back and forth between the icon view and compressed view in this tutorial, as is convenient.
Solution Inside: Want to learn how to create folders yourself? | Show |
---|---|
If it has been a while since you completed the first part of this tutorial series, then you may not remember the state of the project. Run the scene now to refresh your memory.
- Does the zombie walk toward where you click? Yep.
- Does the zombie wander off the screen? Annoying, but yep. You’ll fix that later in this series.
- Does the cat sit on the beach, more lifeless than even a zombie? Completely unacceptable! Time for some animation.
Sprite Animations
In the first part of this series, you animated the zombie’s walk cycle using a script namedZombieAnimator.cs. That was meant to demonstrate how to access the
SpriteRenderer
from within your scripts, which you’ll find can be useful at times. However, here you’ll replace that script to use Unity’s great built-in support for animations.
Select zombie in the Hierarchy and remove the ZombieAnimator (Script) component in the Inspector. To do so, click the gear icon in the upper right of the component and then choose Remove Component from the menu that appears, as shown below:
Note: When testing, sometimes it’s useful to try different things. Rather than remove a component and then replace it later, you can temporarily disable it by unchecking the box to the left of its name, as shown below:
Of course, disabling components is not just for testing purposes. There will be times when you want to enable or disable components at runtime, which you can do from within your scripts by setting the component’s
enabled
flag.
You won’t be using ZombieAnimator.cs anymore in this tutorial, so removing it from zombie is the cleaner option.
Run your scene just to make sure rigor mortis has set in. That is, make sure your zombie isn’t moving those limbs!
To start creating animations, open the Animation view by choosing Window\Animation. As you can see in the following image, you can also add this view to your layout by choosing Animation from the Add Tabmenu connected to any other tab:
Arrange your interface so that you can see the contents of the Animation view and the Project browser at the same time. For example, it might look something like this:
Inside the Project browser, expand zombie to reveal its Sprites, then select zombie in the Hierarchy.
Your interface should look something like this:
Because you selected zombie in the Hierarchy, the Animation view allows you to edit the zombie’s animations. Currently, it has none.
Note: While you would probably expect the Animation view to work with the currently selected GameObject, you might be surprised to find out that it usually continues to operate on the most recentlyselected GameObject.
That means that later, when you select a Sprite asset in the Project browser and Unity clears the Hierarchy’s selection, the Animation view will still operate on the zombie’s animations. This will continue to be the case until you select something else in the Hierarchy.
The term “usually” was used earlier because if you select certain types of assets in the Project browser, such as Prefabs, the controls in the Animation view all disable themselves rather than allow you to continue working on your animations.
Introducing the Animation View
Before creating any animations, it will help if you understand the following three terms:
- Animation Clip: A Unity asset that defines a specific piece of animation. Animation Clips can define simple animations, like a blinking light, or complex ones, such as an attack animation for a seven-headed hydra. Later you’ll learn how you can combine Animation Clips to produce even more complex animations.
- Curve: Changing the values of one or more properties over time is what produces an animation, and Unity refers to each of these animated properties as a curve. Unity uses this term because you can graph the property’s values over time, and lines on a graph are referred to as curves, even if they’re straight. Mathematicians, am I right?
- Keyframe: Rather than define values for every frame of an animation, you will set values at certain points in time and let Unity fill in the gaps by interpolating the values between those points. The points along a curve that you define explicitly are called keyframes, because they are the “frames” in the animation that are “key” to calculating the final result.
With those terms defined, it will now be easier to discuss the Animation view. You use this window to create Animation Clips associated with a specific GameObject. Each clip will consist of one or more curves, and each curve will consist of one or more keyframes.
The following image highlights the different parts of the Animation view, and the list after it provides the names used in this tutorial to refer to these areas, along with a brief description of each:
- Control bar: This area contains various controls you’ll use when working on Animation Clips. These will be described as needed.
- Curves List: The list of curves affected by the current Animation Clip, as well as a button for adding a new property curve.
- Timeline: A view of the animation curves, showing their values over time. The contents of this area will be different depending on the current view mode (see item #4). In Dope Sheet mode, it will contain each curve’s keyframes, laid out horizontally over time. This functions similarly to what traditional animators use in that it is mainly useful for judging the timing of important moments in your animation. However, in Curves mode, the timeline graphs the actual value of the property over the duration of the animation, providing a visual indication of the curve’s values at any point in time.
- View mode buttons: These two buttons allow you to switch the timeline’s view mode between Dope Sheet and Curves modes. This tutorial utilizes Dope Sheet mode exclusively, but each mode can be useful. Generally, you will set up your keyframes in Dope Sheet mode and then use Curves mode if you need to fine tune how the values are interpolated between your keyframes.
Don’t worry if any of the above descriptions don’t seem clear – the Animation view’s various components will be described in detail throughout this tutorial.
Inside the Project browser, click zombie_0 and then shift+click zombie_3, resulting in a selection containing all four zombie Sprites, as shown below:
Now drag the selected Sprites over the Animation view. A green icon with a plus sign in it will appear, as shown below:
When you see the + icon, release the mouse button, which will display a dialog titled Create New Animation. This dialog simply allows you to name and choose a location in which to save your new Animation Clip.
Enter ZombieWalk in the field labeled Save As, choose the Animations directory, and click Save. The following image shows the completed dialog:
Note: One important point is that the dialog included this text: “Create a new animation for the game object ‘zombie'”. You can only create Animation Clips for GameObjects in your scene. That is, you cannot select a Prefab in the Project browser and create animations for it, but you can create animations for an instance of a Prefab that you’ve added to the Hierarchy and then apply those changes back to the Prefab.
When the dialog closes, Unity has done several things for you behind the scenes:
- Added a new Animator component to zombie. Unity plays Animation Clips on a GameObject through this Animator component. You’ll learn more about it in the next part of this tutorial.
- Created a new Animation Clip called ZombieWalk and set up the Animation view to edit it. As you can see below, the Animation view’s clip drop-down menu, in the view’s control bar, now indicates thatZombieWalk is the current Animation Clip:
- Created a new Animator Controller, saved it in the same Animations folder into which you savedZombieWalk, and assigned it to zombie‘s Animator. You can see it in the Controller field in the zombie’sAnimator component here:The Animator Controller is what decides which Animation Clip the Animator should play at any given time and will be covered in the next part of the tutorial.
- Colored some interface elements red. For example, the scene controls shown below:
The other red components are covered in more detail later, but for now, just know that whenever you see a red field or UI component in Unity, you’re currently recording an Animation Clip.
You can only work on one clip at a time in the Animation view. Clicking the clip drop-down allows you to select which Animation Clip to edit from all of the clips associated with a specific GameObject. As you can see in the following image, the zombie currently only has one clip – ZombieWalk.
In the above image, the check mark next to ZombieWalk indicates that this is the current clip selection, which becomes more useful when you have multiple clips in the list. The above image also shows that the menu includes an option labeled [Create New Clip], which allows you to create a new clip associated with the same GameObject. You’ll use this later when animating the cat.
The screenshot below shows how dragging the Sprites into the Animation view automatically added a curve labeled zombie : Sprite:
This means that this animation affects the
sprite
field of the zombie’s SpriteRenderer
component. Sometimes, if the property name is not obvious based on the components attached to the object, the property name will include the name of the component as well. For example, if you wanted to animate the enabled
state of the SpriteRenderer
, it would be labeled zombie : SpriteRenderer.enabled.
Select zombie in the Hierarchy (or select zombie : Sprite in the Animation view’s curves list, which automatically selects zombie in the Hierarchy), and then look at the Sprite Renderer component in theInspector. As the following image shows, the Sprite field is tinted red. This not only indicates that you are recording an Animation Clip, but that the clip you are recording specifically affects this field.
In the Animation view’s timeline, you can see that Unity added four keyframes to the Sprite curve. If you can’t see the frames as clearly as you can in the following image, try zooming in on the timeline by scrolling with your mouse wheel or by performing whatever scroll operation your input device supports.
Along the top of the timeline you’ll see labels that consist of a number of seconds followed by a colon and then a frame number.
Values start counting at zero, so 0:02 indicates the third frame of the first second of animation. I wanted to use1:02 as the example, but I was afraid the phrase “third frame of the second second” might be confusing. ;]
As you can see, Unity placed the four sprites at 0:00, 0:01, 0:02 and 0:03.
Before doing anything else, try running the clip by clicking the Play button in the Animation view’s control bar.
Be sure that the Animation view is visible along with either the Scene view or the Game view so you can see the zombie strutting his stuff. Or, to put it more accurately, watch as he apparently gets electrocuted.
If that were Unity’s idea of good animation, you’d have to resurrect that script you removed earlier. Fortunately, this isn’t a problem with Unity; it’s just a problem with ZombieWalk‘s configuration.
Click the Animation view’s Play button again to stop the preview.
Note: While previewing an Animation Clip, the Animation view must be visible. If you have it open as part of a tabbed layout and you switch away from it to another tab, the animation will immediately pause.
You may recall from the first installment of this series that the zombie’s walk cycle ran at ten frames per second. However, if you look at the field labeled Samples in the Animation view’s control bar, you’ll see it is set to 60:
The Samples field defines an Animation Clip’s frame rate and it defaults to 60 frames per second. Change this value to ten, and notice how the timeline’s labels now go from 0:00 to 0:09 before moving to 1:00:
Preview your animation again by clicking the Animation view’s Play button. You should see the zombie moving at a much more reasonable pace:
The zombie is looking better already, but he’s not quite his old self yet. That’s because the animation you defined only includes the first four frames of the walk cycle, so when it loops it jumps from zombie_3 back tozombie_0. You need to add some more frames to smooth this transition.
Select only zombie_2 in the Project browser and drag it over the Animation view. Position your cursor inside the zombie : Sprite row in the timeline, just to the right of the last keyframe, and release your mouse button, as shown below:
You should now have keyframes at 0:00 through 0:04. However, depending on your zoom level, it’s pretty easy to accidentally place the new keyframe too far to the right. For example:
If this occurs, simply drag the keyframe to the left using the small diamond above the curve, as shown below:
Now repeat the previous process to add zombie_1 to the end of the animation, which is frame 0:05. YourAnimation view now looks like this:
Test your animation again by pressing the Play button in the Animation view. Your zombie is finally strutting his stuff.
With your Animation Clip complete, run your scene and make sure the zombie still moves around properly while animating.
You’ve successfully replaced the zombie’s script-based animation with an Animation Clip. That may have seemed like a lot of effort, but it was really just a lot of words describing the UI. If you break down what you actually did, you basically dragged some sprites into the Animation view and set a frame rate. Darn, now I’m kicking myself for not just writing that in the first place.
Note: If you didn’t already have a zombie GameObject in your Scene, you could have tried an even easierway to create and animate the zombie.
If you simply select a group of Sprites in the Project browser and drag them directly into the Scene orHierarchy views, Unity does everything you saw earlier, like creating an Animation Clip, an Animator and an Animator Controller. However, it also creates a GameObject in the Scene and connects everything to it! I’m guessing that by Unity 5.0, you’ll just have to drag your Sprites into the Scene and Unity will automatically create the correct gameplay based on the art style. You heard it here first!
Ok, you’ve gotten your feet wet with animations in Unity, but there is still plenty left to learn. Fortunately, you’ve got a perfectly good cat to experiment on just sitting there.
Animating Other Properties
Unity can animate things other than Sprites. Specifically, Unity can animate values for any of the following types:
- Bool
- Float
- Color
- Vector2
- Vector3
- Vector4
- Quaternion
- Object Reference
Note: The above list was copied verbatim from Unity’s documentation here.
For the zombie, you won’t modify anything other than the Sprite, but over the lifetime of a cat, it will move through the following sequence of animations:
There are actually five different Animation Clips at work here:
There are actually five different Animation Clips at work here:
- Rather than have cats just appear on the beach, you’ll animate them in from nothingness.
- The cats will wiggle back and forth to attract the zombie’s attention.
- When the zombie touches a cat, the cat will turn into a zombie itself. You’ll transition it from white to green to give it a nice, undead look.
- By combining this simple scaling animation with forward motion, it will give the impression that the cats are happily hopping along in their conga line…of dooooooooom!
- When the old lady hits your player’s zombie, you’ll remove some cats from the scene. Rather than just make them disappear, you’ll spin them into nothingness, signifying their mad descent into wherever kitties go after they die after having already died once. Poor little twice-dead kitties.
You’ll produce each of those animations without any additional artwork. Instead, you’ll animate the cat’s scale, rotation and color properties.
Create the Cat’s Animation Clips
Select cat in the Hierarchy. Remember, Unity decides where to attach new Animation Clips based on the most recent Hierarchy selection.
In the Animation view, choose [Create New Clip] from the clip drop-down menu in the control bar, shown below:
In the dialog that appears, name the new clip CatSpawn, select the Animations directory, and click Save.
Unity automatically adds an Animator component to the cat when you create the first Animation Clip. As you make each of the following clips, Unity will automatically associate them with this Animator.
Repeat the above process to create four more clips, one for each of the other animations you’re going to make. Name them CatWiggle, CatZombify, CatConga and CatDisappear.
The Animation view’s clip drop-down menu now contains all five clips, as shown below:
Note: When creating a new Animation Clip, the dialog Unity displays defaults to showing whatever folder you are currently viewing in the Project browser. You can save yourself from having to repeatedly choose the Animations folder in this dialog by navigating to the Animations folder in the Project browser beforeyou create the clips.
Of course, if you created the clips before you read this note for some silly reason, like because those instructions came before this note, well then one of us made a serious mistake in our order of operations, didn’t one of us?
Adding Curves Automatically
This tutorial will show a few different techniques for setting up Animation Clips. For the zombie’s walk cycle, you dragged Sprites into the Animation view and Unity created all the necessary components automatically. This time, you’ll start with an empty clip to edit and let Unity add the curves for you.
Select cat in the Hierarchy, then select CatSpawn from the Animation view’s clip drop-down menu to begin working on this clip, as shown below:
To enter recording mode, press the Record button in the Animation view, shown below:
Once again, Unity indicates that you are now in recording mode by tinting red the Animation view’s Record button, the scene controls, and the checkbox next to the cat’s Animator component. The Record button while recording is shown below:
For the cat’s spawning animation, you simply want to scale the cat from zero to one. In the Inspector, set theScale values for X and Y to 0. A 2D object’s scale along its z-axis has no effect, so you can ignore the Scale’s Z value.
Your Transform component in the Inspector now looks like this:
As soon as you adjusted one of the Scale fields, they all turned red in the Inspector to indicate that you are currently recording an animation for the cat that contains a Scale curve. Unity automatically added a curve to your Animation Clip named cat : Scale, shown below:
Look in either your Scene or Game views and you will see that your cat just disappeared!
Technically, the cat is still located right where it was, but without a width and height, you can’t see it. That’s because while recording an animation, your Scene and Game views display the GameObject as it appears in the frame currently selected in the Animation view. But what frame is selected in the Animation view?
Take a look at the Animation view’s timeline, which now includes a single keyframe at 0:00 on the cat : Scalecurve, as shown below:
The vertical red line you see in the above image is the scrubber. Its position indicates your current frame in the animation. Any changes you make will be recorded at this frame, creating a new keyframe there if necessary. Also, as was previously mentioned, the Scene and Game views will display your GameObject as it will appear during this frame of animation.
The scrubber appears whenever you are in recording mode, as well as while previewing your animation with the Animation view’s Play button.
The Animation view’s control bar includes a current frame field that indicates the frame at which the scrubber is located. As you can see below, it is currently at frame zero:
Type 15 in the frame field to move the scrubber to frame 15. Because this clip is set to run at 60 frames per second, the scrubber is now at 0:15, as the following image shows:
Note: You can move the scrubber by setting its position in the control bar’s frame field like you just did, or by positioning it directly in the timeline view. To position the scrubber directly, simply click and/or drag in the upper area of the timeline, where the frame labels are displayed.
In the Inspector, set the cat’s X and Y values for Scale to 1, as shown below:
Press the Play button in the Animation view to preview your animation. Inside the Game or Scene views, watch your cat scale up to full size and then disappear, over and over again.
Click the Record button in the Animation view to exit recording mode.
Note: Besides using the Animation view’s Record button, Unity will also exit recording mode if you save or play the current scene.
Play your scene and notice that the cat still flashes continuously in and out of existence. Hmm, that wasn’t just a feature of the Animation view’s Preview mode?
Everyone loves a pulsating cat, but that’s not really what you were going for. The problem is that Animation Clips in Unity loop by default, but this should really be a one shot deal.
Select CatSpawn in the Project browser to view the Animation Clip’s properties in the Inspector. Uncheckthe box labeled Loop Time to disable looping, as shown here:
Note: This tutorial doesn’t cover any of Animation Clip’s other options that you can see in the Inspector. They are primarily useful for dealing with animations associated with 3D models. To learn more, see Unity’s Animation Clip documentation.
Play the scene again and the cat pops in before remaining very, very still.
Note: If it’s too hard to see the animation, you can temporarily decrease the samples to 10 like you did earlier to slow down the animation. Just be sure to set it back when you’re done!
You’d think it would want to draw a little more attention to itself to attract the zombie, right? Well, nothing attracts zombies like a wiggling cat, so it’s time to make it wiggle.
Adding Curves Manually
It’s perfectly fine to let Unity add any necessary curves for you based on changes you make while recording a clip, but sometimes you’ll want to add a curve explicitly from within the Animation view.
Select cat in the Hierarchy, and then choose CatWiggle from the clip drop-down menu in the Animationview’s control bar.
Click Add Curve to reveal the following menu:
This menu lists each Component on the associated GameObject. Click the triangle next to Transform to reveal the properties available for animating, and click the + icon on the right side of Rotation to add a Rotation curve, as demonstrated below:
Note: You can – and will – add multiple properties to a single Animation Clip. When you open this menu, it won’t show any properties that you’ve already added to the clip. Likewise, if you add all of the properties for a given Component, that Component will no longer appear in the menu. This makes it easy to find the property you want to add.
Inside the Animation view, click the triangle to the left of cat : Rotation to expose curves for the x, y and z rotation properties. Unity gives you three curves so you can manipulate each component of the rotation individually, and as you can see in the following image, Unity automatically added keyframes at frames 0 and 60 of each curve it created:
Each of the keyframes Unity added has the same values – whatever ones existed on the GameObject when you added the curve. In this case, the rotations are all zero, as shown below:
Note: You will only see the values shown in the above image while you are either recording or previewing a clip. Otherwise, your curves will look like this:
Inside the Animation view, make sure the scrubber is at frame zero. Move your cursor over the 0 next toRotation.z, and notice that it highlights to indicate that it’s actually a text field, as shown below:
Click in the Rotation.z field and change the value to 22.5, as shown below:
Now move the scrubber to frame 30 and set the Rotation.z value to -22.5. Unity automatically creates a new keyframe here to store this new value, as shown below:
Finally, move the scrubber to frame 60 and set the Rotation.z value to 22.5.
Press the Play button in the Animation view to preview the rotation. Be honest, that cat’s soothing oscillation makes you want to tape a cat to a fan, doesn’t it?
To make the cat look more like it’s hopping around rather than just swiveling from side to side, you’ll add a bit of scaling to the animation. Basically, you want the cat to be its normal size at the extremes of its rotation, and a bit larger right in the middle.
With what you’ve practiced already, you should have no problem adding a Scale curve to CatWiggle. Do so now.
Solution Inside: Don't remember how to add a curve? | Show |
---|---|
The rotation is at its most extreme values at the keyframes you placed at 0, 30 and 60, so it’s at its midpoint at frames 15 and 45. That means you’ll want to increase the scale at these two frames.
Set the X and Y Scale values to 1.2 at frames 15 and 45, and set them to 1 at frames 0, 30 and 60.
You’ve learned two different ways to set values, so give it a try yourself.
Solution Inside: Need a refresher on setting values for keyframes? | Show |
---|---|
When you’re done, you should have keyframes that look like this:
Preview the animation by clicking the Play button in the Animation view. Your cat should now look quite enticing to a hungry zombie:
Now run your scene. Hmm, the cat still just pops in and then stays perfectly still, like it just saw a ghost or something else equally terrifying.
The problem is that you have more than one Animation Clip associated with the cat, so now you need to make sure the cat plays the correct animation at the correct time. To do that, you need to configure the cat’s Animator Controller, which you’ll learn how to do in the next part of this tutorial!
Bonus: Animation View Extras
Here are a couple extra bits of information about the Animation view that you may find useful.
Curves Mode
While this tutorial didn’t cover the Animation view’s Curves mode, you’ll probably find you need to use it at some point to fine-tune your animations.
In Curves mode, the timeline displays a graph of the selected curves. The following image shows the Animation view in Curves mode with both the Rotation.z and the Scale.x curves selected:
You can use this mode to add, delete and move keyframes, as well as set values for keyframes like you did in Dope Sheet mode. However, the real power of Curves mode comes from its ability to adjust the valuesbetween the keyframes.
If you select any keyframe, you can access a menu of options by either right-clicking on it, which is often tricky to accomplish, or by clicking the diamond for that curve in the curves list, as shown below:
The options in the menu allow you to control the curve between the keyframes. By selecting an option likeFree Smooth, Flat, or Broken, you can then click on a keyframe in the timeline and access handles to control how the curve enters/exits that keyframe, as shown below:
Working directly with the curves can be tricky and error prone; it’s certainly not an exact science. But if you aren’t happy with the timing of one of your animations, playing around with these options can sometimes help.
Editing in Preview Mode
You probably already know that if you make any changes to your GameObjects while playing a scene in the editor, these changes are lost when you stop the scene. However, this is not the case when previewing Animation Clips using the Animation view’s Play button.
That means that you can tweak the values of a clip while it loops in preview mode until you get them just right. This can come in handy sometimes, such as when adjusting curves in Curves mode or when adjusting a clip’s timing by moving keyframes.