Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Unity 5.x Animation Cookbook
Unity 5.x Animation Cookbook

Unity 5.x Animation Cookbook: An advanced solution to all your Animation problems

eBook
£20.98 £29.99
Paperback
£36.99
Subscription
Free Trial
Renews at £16.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. £16.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Unity 5.x Animation Cookbook

Working with Animations

This chapter explains the essentials of working with animations in Unity and covers the following topics:

  • Importing skeletal animations
  • Configuring generic and humanoid rigs
  • Creating and assigning an Animator Controller
  • Creating animation transitions in Animator Controller
  • Using parameters to control the animation flow
  • Using animations from multiple assets
  • Looping mirroring and offsetting animations
  • Adjusting the playback speed of animations
  • Using override Animator Controllers to animate different types of characters
  • Importing object animation from a 3D package

Introduction

Unity is a great game engine that implements the animate everything philosophy, which allows you to visualize even the most creative gameplay ideas. Through the course of this book, we will learn a variety of recipes that will help you unleash the power of Unity 5.x animation tools and make your games more fun.

In this first chapter, we will get more familiar with using skeletal animations in Unity. It will guide you through the process of importing such animations, editing them, and assigning them to your in game characters. This knowledge is essential for understanding recipes described in further chapters.

Importing skeletal animations

This first recipe shows how to import a skeletal animation from a 3D package. It assumes that you have an animation already prepared. We are going to bring the file to Unity and show where you can adjust the import settings. We will not jump into too much detail for now to make the import process as quick as possible. We will cover all the settings in further recipes.

Getting ready

Most animations are created in external 3D packages such as Maya, 3ds Max, Motion Builder, or Blender 3D. Make sure you have prepared a 3D model with a skeleton, the model is skinned, and you have created at least one animation. You can also download the provided example; open the project in Unity and go to this folder: Chapter 01 Working with animations\Recipe 01 Importing skeletal animations\Sheep Model. You will find an imported FBX file called Sheep.fbx there.

How to do it...

To import a skeletal animation, you need to follow these steps:

  1. Export a skinned model and its skeleton (called rig in Unity) to FBX format.
If you are using Blender, you don't have to manually export the file to FBX format. Simply drag and drop the file to your Assets folder. Unity will use Blender FBX exporter in the background. Additionally, you will be able to open the file by double-clicking on it in Unity. After you edit and save it, Unity will reimport it again. It is a very convenient way of editing animations as you don't have to go through the export-import process each time you make a change.
  1. Drag and drop the exported file into any subfolder in the Assets folder in your project or go to AssetsImport new asset and choose your FBX file.
  1. Select the imported file and navigate to the Inspector tab. Click on the Rig button:
  1. Here you can specify the type of the rig to use. For bipedal characters, use the Humanoid option, for all the rest choose Generic. We use a sheep model in this example, so we need to choose the Generic rig. Differences between those options are described in the How it works section.
  2. Leave all the other inputs as defaults.
  1. Click on the Animations button. If an Unapplied import settings window appears, click on Apply.
  1. Make sure the Import Animation checkbox is checked.
  2. Click on the Apply button in the lower right corner of the Inspector (just above the Animation Preview). You may need to scroll the Inspector down.
  1. You should be able to see all imported animation clips as child assets of your imported FBX file.

How it works...

Unity uses four different rig configurations:

  • Generic rig: This one is used for quadrupeds, spiders, and other non-humanoid characters. It uses Unity's Mecanim system for controlling animation flow. It can use root motion if you provide a Root nodea bone responsible for character movement.
  • Humanoid rig: This one is used for humanoid characters only. It also uses Mecanim system for controlling animation. If you are using Humanoid rigs, you have more options for importing animations. The biggest advantage is automatic animation retargetingyou can use the same animation clip on various types of humanoid characters (for example, a dwarf and a troll).
  • Legacy: This option is used mostly for backward compatibility with previous versions of Unity. It is similar to the Generic rig but uses scripts instead of Mecanim for controlling animation flow. I recommend using Generic rig instead.
  • None: This last option turns off the rig and disables animation import.

We will discuss differences between Generic and Humanoid rigs further in the next recipe.

There's more...

  • Imported animation clips are also listed in the Clips section of the Animations tab.
  • You can add new clips by clicking on the plus button below the Clips section. You can also remove clips by clicking on the minus button.
  • You can rename each clip by using the input field above the Source Take drop-down menu.
  • You can choose the source take (the animation stored in your FBX file) for each animation clip with the Source Take drop-down menu.
  • You can also trim the animation clip by editing the Start and End input fields.
If you are using Blender, make sure to rotate the rig -90 degrees in the X axis, apply the rotation in Blender and then rotate it again, +90 degrees in the X axis. The rotation of the rig in Blender should be: 90 X, 0 Y, and 0 Z. Your model should be facing the -Y axis in Blender (when you change the view to FRONT, you should see the face of your character). Blender and Unity use different axes alignment: in Blender, Z is up and Y is back; in Unity Z, is front and Y is up. This little trick solves the problem. Your model after import should have 0 rotation and should be facing the Z axis. It is important for moving objects (such as characters) and rig configuration. If you don't do this, your model will have -90 X rotation after the import.

Configuring generic and humanoid rigs

This recipe shows how to configure two most frequently used rig types: Generic and Humanoid. We will go through all the available options for both of them.

Getting ready

As previously mentioned, make sure you have prepared two animated characters. One of them should be a humanoid and the other a non-humanoid, a quadruped for instance. You can also download the provided example Unity project and go to the Chapter 01 Working with animations\Recipe 02 Configuring generic and humanoid rigs\Rigs directory.

You will find there three FBX files: 

  • Generic.fbx
  • Humanoid.fbx
  • Quadruped.fbx

If you are creating your characters from scratch, the bones hierarchy of your humanoid rig is important for Unity to recognize the rig as a humanoid. It should follow this pattern:

HIPS -> SPINE -> CHEST -> NECK -> HEAD 
HEAD -> EYE (for left and right eyes) 
HEAD -> JAW 
HIPS -> UPPER LEG -> LOWER LEG -> FOOT -> TOES (for left and right legs) 
CHEST -> SHOULDER -> ARM -> FOREARM -> HAND (for left and right hands) 
HAND -> PROXIMAL -> INTERMEDIATE -> DISTAL (for five fingers in left and right hands) 

The hip bone is the root bone of the humanoid character. Fingers, shoulders, chest, neck, eyes, jaw, and toes are optional bones. Your humanoid character will work without them.

You should also remember to model the character in a T-POSE. It should face the Z axis in Unity (if your 3D software uses different axis alignment from Unity's like Blender, remember about the -90 and +90 degrees rotation trick shown in the Importing skeletal animations recipe). Hands of the character should be flat, palm down, and parallel to the ground along the X axis. A-POSE characters will also work.

How to do it...

To configure a generic rig you need to follow these steps:

  1. Import your animated asset into Unity the same way as in the Importing skeletal animations recipe.
  2. Select the asset and choose the Rig tab in the Inspector. Then select the Generic option in the Animation Tab drop-down menu. If you are using the provided example Unity Project, select the Generic.fbx file in the Chapter 01 Working with animations\Recipe 02 Configuring generic and humanoid rigs\Rigs directory.
  3. Choose the Create From This Model option from the Avatar Definition drop-down menu.
  4. Leave the Root Node option set to None.
  5. Leave the Optimize Game Objects option unchecked.
  6. Click on the Apply button to complete the configuration.

Humanoid rig configuration has a lot more options:

  1. First, import your skinned humanoid model to Unity the same way as in the Importing skeletal animations recipe.
  2. Select the asset and choose the Rig tab in the Inspector. Then select the Humanoid option in the Animation Tab drop-down menu. If you are using the provided example Unity Project, select the Humanoid.fbx file in the Chapter 01 Working with animations\Recipe 02 Configuring generic and humanoid rigs\Rigs directory.
  3. Choose the Create From This Model option from the Avatar Definition drop-down menu.
  4. Leave the Optimize Game Objects option unchecked.
  5. Click on the Apply button.
  6. You should see a Configure button with a tick icon near to it.
  1. The tick icon shows that Unity was able to automatically recognize the rig hierarchy as a humanoid. If Unity fails to recognize it, automatically a cross will be displayed instead of the tick. If you are using the provided example, you can observe it when you try to set the rig to Humanoid for the Generic.fbx file.
Some quadruped characters can be mistaken by Unity for humanoids. You can find a Quadruped.fbx file in the provided example Unity project. Theoretically, you can set its rig to Humanoid, and Unity will recognize it as valid. This, however, is a mistakeall quadruped characters' rigs should be set to Generic. Setting them as humanoids can cause problems later.
  1. Click on the Configure button to enter the Avatar Configuration Inspector. A new scene will be opened. You should be able to see your model in the scene and bone mapping section in the Inspector tab.
  1. Make sure you are in the Mapping section (1). All recognized and assigned bones are shown as green body parts on the displayed dummy character. If a required bone is missing or is not assigned, it will show up as red. You can navigate between the BodyHeadLeft Hand, and Right Hand sections by clicking on a corresponding button (2). All bones are displayed in a list (3) for each section. Required bones are marked with circle icons and optional bones are marked with dotted circle icons.
  2. You can change the bone assignment by dragging a bone from the Hierarchy tab and dropping it onto a corresponding bone slot in the Inspector tab. Unity will occasionally miss a bone or two (especially fingers); thus, you should always check the bone assignment manually.
  3. If your character is not in a T-POSE (is modeled in an A-POSE for instance), a Character is not in T-POSE message will be displayed in the scene view and the character's bones will show up in red. Unity needs the character in a T-POSE for proper humanoid avatar configuration. You can enforce that pose by choosing the Pose |Enforce T-POSE option, found below the bones mapping list.
  1. Click on the Apply button and then the Done button to finish configuration.

How it works...

Humanoid rig uses more advanced Mecanim features than the Generic rig. You can find the list of such features below:

  • Automatic retargeting: This is one of the most important differences between those two rigs. The Humanoid rig uses automatic retargeting, which means that you can have the same animations on different humanoid characters. Your characters can share a group of animations (basic movement or some common actions). It gives you the possibility to buy your animation assets from the Asset Store and easily use them on your characters. Generic rigs don't support this feature. You have to prepare animations for your specific rig or retarget them in a 3D package.
  • Inverse kinematics: This feature lets you control your characters' feet and hands position with scripting. It is useful for making your characters stand on uneven ground or grab an object in the scene. It is a built-in feature for Humanoid rigs in Unity. Generic rigs have to use custom-made solutions.
  • Advanced animation settings: Humanoid rigs have more settings for animation import, such as the mirror option. We will discuss them in depth in the Looping mirroring and offsetting animations recipe.
  • Look at: Unity has a built-in solution for humanoid characters looking at something. You have to write custom systems for generic characters.
  • Additional bones: A lot of people think that they cannot use additional bones with Humanoid rigs. It is not true. If your rig has an animated weapon slot for instance, you can still use it with the Humanoid rig. All you need to do is to find the Mask section in your animation import settings and enable the additional bone for each animation it is used in (you need to use the Transform foldout to find your additional bone).

I highly recommend using Humanoid rigs for all humanoid characters in your game.

There's more...

  • In the Humanoid rig configuration, you can find the Muscles & Settings section, where you can preview and adjust the movement (muscle) range for your character.
  • You can preview the range of movement in the Muscle Group Preview section by adjusting the sliders (1). You can preview the range of movement per muscle in the Per-Muscle Settings section. You can also adjust the range here by unfolding a given muscle foldout and using the slider (2). In the Additional Settings section, you can adjust more options of your avatar. These are mainly responsible for the flexibility of your rig. You can set how much a bone can be stretched during animation for instance.
  • The Translation DoF option enables animating bones transition in your Humanoid rig. It is turned off by default, meaning that only rotation of the bones is used in animation.
  • In the Rig tab in the model import settings, you can find some additional options:
    • Avatar Definition: This option is responsible for creating a new avatar or copying the avatar from another model. The second option is useful for storing animations in multiple files. It will be discussed further in the Using animations from multiple assets recipe.
    • Optimize Game Objects: This option lets you hide all bones from the Hierarchy view. The number of game objects in the game has an impact on the performance. You can still choose a number of bones that will be displayed in the Hierarchy. It is useful for having exposing weapon slots and similar gameplay-related bones while hiding others.
    • Root node: This option is visible only for Generic rigs. It lets you choose the bone responsible for root motion calculation. We will discuss it further in Chapter 4Character Movement.

Creating and assigning an Animator Controller

Animator Controllers are state machines (graphs) responsible for controlling the flow of animations of any animated object in the game. The same Animator Controller asset can be used by multiple objects or characters. Unity will create an independent runtime copy of the asset for each animated object it is assigned to.

Getting ready

As always, you should have a rigged and animated character ready before we start. Import it into Unity, choose the proper rig type, and put it into a scene. You can download the example Unity project and go to the Chapter 01 Working with animations\Recipe 03 Creating and assigning an animator controller directory. There is a scene called Example.unity there. If you open it, you'll find a Sheep character in the Hierarchy. It has an Animator Controller already created and assigned. You can also use the Quadruped.fbx file from the Chapter 01 Working with animations\Recipe 03 Creating and assigning an animator controller\Rigs directory to follow the recipe step by step.

How to do it...

To create and assign an Animator Controller, follow these steps:

  1. Navigate to the Project View (any directory in the Assets folder) and press  the right mouse button.
  2. Choose CreateAnimator Controller from the menu. A controller asset will be created. You can name it as you wish.
  3. Double-click on the created controller. An Animator tab will appear. It will show the current selected Animator Controller.
  1. Here you can add the first animation. Navigate to your imported character in the Project View. Unfold it and drag and drop one of the imported animations into the Animator window. A new state will be created and will be colored orange, showing that this is the default animation statethe state from which your graph starts.
  1. Navigate to your character on the scene and select it.
  2. Find the Animator component in the Inspector tab. All animated objects have an Animator component added automatically.
  3. Find the Controller slot in the Animator component inspector.
  4. Drag and drop your Animator Controller asset into the Controller slot of the Animator component.
  5. Run the game to see your character play the default state animation of your Animator Controller. If the animation is not looped, it will be played just once and then the character will freeze.
  6. You can also select your character in runtime and navigate to the Animator tab to see what animation state the character is currently in. Current animation state will have a blue progress bar displayed.

How it works...

Every animated object in Unity uses an Animator component and an Animator Controller asset. The component is responsible for playing animations in runtime. It has a number of parameters that we have to set or we can use to tweak the component's functionality:

  • Controller: This is the field we have to attach the Animator Controller asset to. It determines which animation graph the Animator component will use.
  • Avatar: In Unity, Avatars are rig definitions. For instance, if we have multiple files containing animations with the same Generic rig, we should use the same Avatar for all of them. You can find more information about it in the Using animations from multiple assets recipe.
  • Apply Root Motion: With this checkbox, we can turn the root motion on and off. It can be useful when we have animations with root motion but don't want to use the root motion definition for a given character.
  • Update Mode: This parameter tells Unity in which update the animations should be evaluated. The Normal option makes the animations synchronized with the normal Update() call, the Animate Physics option synchronizes animations with the physics FixedUpdate() call, and the Unscaled Time option synchronizes the animation with the normal Update() call, but disables animation time scaling (the animation is played with 100 percent speed regardless of the Time.timeScale variable value).
  • Culling Mode: This parameter tells Unity when to turn off the animation playback on a given Animator. The Always Animate option makes the Animator always play animations (event when off-screen), the Cull Update Transforms option culls Retarget and IK Transforms when the Animator is not visible on screen, and the Cull Completely option disables the animation completely when the Animator is not visible on screen.

The Animator Controller asset stores a graph of animations (animation states) and defines the rules of switching between them, blending them, and so on. The controller (asset) is attached to the component's Controller field (the component is attached to a character prefab or a character placed in the scene). Many objects or characters can share the same Animator Controller if they use the same animations (have the same rigs or are humanoid characters).

See also

If you want to learn how to create animation graphs and control their flow, see the next two recipes: Creating animation transitions in Animator Controller and Using parameters to control the animation flow.

Creating animation transitions in Animator Controller

As mentioned previously, Animator Controllers are state machines containing animations (states). Any given character can be in one such state (play one animation) at a time. To switch between states (animations), you need to create state transitions.

Getting ready

Before we start, you should have an animated model placed on a scene with an Animator Controller assigned. You can find such a model in the provided example Unity project. Go to the Chapter 01 Working with animations\Recipe 04 Creating animation transitions in Animator Controller directory. Open the Example.unity file. You will find a Sheep object in the Hierarchy. It has an Animator Controller assigned. You can open it by double-clicking on the Controller field in the Animator component of the Sheep game object.

How to do it...

To create a state transition in an Animator Controller, follow these steps:

  1. Open the Animator Controller asset.
  2. Add at least two states by dragging and dropping two animations into the Animator window. You can also point the cursor at an empty space in the Animator window, press the right mouse button and select Create StateEmpty, then select the state, and add an animation to the Motion field in the Inspector.
  3. Click on the right mouse button on the state you want to transition from and choose Make Transition.
  4. Drag the transition onto the state you want to transition to and click the left mouse button.
  1. A default transition will be created. The state will switch after its animation has finished playing. To be able to observe it in gameplay, make sure you transition from the default (orange) state, as only the default state will play when the game starts.

How it works...

State transitions define how we can travel through the graph of animations. They are combined with transition conditions based on Animator Controller parameters; we will discuss the parameters in detail in the next recipe: Using parameters to control the animation flow. Each transition has a set of properties we can adjust. Click on the transition (white arrow) to select it. You can find the transition properties in the Inspector tab (make sure to unfold the Settings foldout):

  • Has Exit Time: If set to true, this enables the transition only after a given percentage of the animation has been already played. If disabled, the transition will take place instantly after its conditions are met. If you want to create a sequence of animations, set it to true.
  • Exit Time: This is the percentage (0-1 range) of the animation length after which the Has Exit Time condition is met. If you set it to 0.5, for instance, the state will transition after 50 percent of the animation was played.
  • Fixed Duration: This property is combined with the next one, Transition Duration (s). If it's on, the Transition Duration (s) is in seconds, and if it's off, the Transition Duration (s) is in percentage of the animation time.
  • Transition Duration (s): the time of the state transition. This is how long the animations will transition one into another. Animations are being blended together during the transition. Longer transitions are smoother, shorter, are more sharp. A good default value is around 0.25.
  • Transition Offset: This offsets the target animation in time. The value is in percentage of the animation. Setting it to 0.3 means that the target animation will start from 30 percent of its length instead of the beginning.
  • Interruption Source: This setting tells Unity whether the transition can be interrupted by other transitions. You can set it to:
    • None: the transition cannot be interrupted by any other transition.
    • Current State: The transition can be interrupted by transitions from the state we are trying to transition from.
    • Next State: The transition can be interrupted by transition from the state we are trying to transition to.
    • Current State then Next State: The transition can be interrupted by the transitions of the state we are trying to transition from or by the transitions of the state we are trying to transition to. The transitions from the state we are trying to transition from take the priority.
    • Next State then Current State: The transition can be interrupted by the transitions of the state we are trying to transition from or by the transitions of the state we are trying to transition to. The transitions from the state we are trying to transition to take the priority.
    • Ordered Interruption: If set to false, this lets the transition be interrupted by other transitions independently of their order. If set to true,the order of the transitions matters.

There's more...

When you create an Animator Controller, you can see three more nodes apart from your animation states:

  • Entry and Exit: This node is used when you transition between state machines (Animator Controllers or substate machines). We will discuss it in detail in the Using Sub-State Machines in Animator Controller recipe in Chapter 6Handling Combat.
  • Any state: This node can be used as a helper to make a transition from any state to a given state. It is used when you have an animation that can be played anytime, for instance, a hit animation. We will discuss it in detail in the Using transitions from any state to play hit reactions recipe in Chapter 6Handling Combat.

Using parameters to control the animation flow

You can define a set of parameters in an Animator Controller and use them to control the transitions between animation states in Mecanim. In this recipe, we will show how to use parameters for transition conditions and use scripts to set values of those parameters in runtime.

Getting ready

Before we start, you should prepare an Animator Controller with at least one transition between animation states. The controller should be assigned to a character (its Animator component) placed in a scene. You can also use the provided example Unity project and go to the Chapter 01 Working with animations\Recipe 05 Using parameters to control the animation flow directory. You will find an Example.unity scene there. There is a Warrior game object in the scene's Hierarchy. If you run the game and press the space bar, the Warrior will make a wave gesture. You can select the Warrior and open his Animator Controller. If you click on the IdleWave transition, you will be able to see the transition condition.

How to do it...

To use parameters for controlling state transitions, follow these steps:

  1. Open the Animator Controller asset.
  2. Find the Parameters tab in the upper left corner of the Animator window and click on it.
  3. Click on the plus icon in the Parameters tab to add a new parameter.
  4. Choose the Trigger type for the parameter.
  5. Type a name of the newly created parameter (in the provided example, the name of the parameter is Wave).
  6. Click on the transition between states you want to use parameters for. In the provided example, it is the transition between Idle and Wave animation states. Idle is the default state.
  7. Go to the Inspector tab and find the Conditions section.
  1. Click on the plus icon to add a new condition. If you have only one parameter, it will be chosen as the condition automatically. If you have more parameters, you need to choose the proper one from a drop-down list.
  1. If you want to make an immediate transition between your animation states, make sure to disable the Has Exit Time option, found above the Settings foldout.
  2. Your transition will take place only when its conditions are met. You need to set the parameter using scripts.
  3. To create a new C# script, click on the right mouse button in the Project View and select CreateC# Script. Name the script as you wish (in the provided example, it's called Wave, the same as the parameter it sets).
  4. Open the script and write the following:
      using UnityEngine; 
      using System.Collections; 
 
      public class Wave : MonoBehaviour { 
      //The anim variable is used to store the reference 
      //to the Animator component of the character. 
      private Animator anim; 
      void Start () { 
      //We get the component and assign it to 
      //the anim variable when the game starts 
      anim = GetComponent<Animator>(); 
      } 
      void Update () { 
      //We check if player pressed the spacebar 
      if (Input.GetKeyDown(KeyCode.Space)) 
      { 
      /*We cal the SetTrigger() function on the 
      Animator component stored in the anim 
      variable. The function requires one 
      parameter - the name of the trigger 
      parameter set in our Animator Controller 
      ("Wave" in our example). Make sure to match 
      it with the name of the parameter you've 
      created in your Animator Controller*/ 
      anim.SetTrigger("Wave"); 
      } 
      } 
      } 
  1. Make sure your class name is the same as the file name of the script, as it won't compile otherwise.
  2. Assign the script to the character, to the same Transform that has the Animator component with your Animator Controller attached. Play the game and press the space bar; you should see your character switch to the next animation state.

How it works...

You can use several types of parameters and corresponding script functions to set them:

  • Trigger: This is the simplest parameter. It is set to true with the SetTrigger(string name) function called on the Animator component object. It is reset by the Animator Controller after it is consumed (used) by a transition. The string name parameter of the function has to match your trigger parameter name set in the Animator Controller.
  • Int: This is an integer parameter. When you use it, you have to specify a logical comparison in the condition. The transition will only occur if the value of the parameter meets the comparison condition with a given number. You can use the EqualGreaterLess, and Not Equal options to compare the value of your parameter with the given number. Integer type parameters are set with the SetInteger(string name, int value) function. The string name parameter needs to match the parameter name set in the controller. The int value parameter is the value to set the controller parameter to.
  • Float: This is a float parameter. It works the same as the integer type, but uses floating point numbers instead of integers. It is set using the SetFloat(string name, float value) function.
  • Bool: This is a Boolean parameter. The condition can check if the parameter is true or false. The value of the parameter is set with the SetBool(string name, bool value) function.

There's more...

  • You can add more than one condition to a state transition by clicking on the plus icon in the Conditions section in the transition Inspector. For the transition to occur, all its conditions have to be met. It works as logical AND for the conditions.
  • You can also create more than one transition between the same states. To do this, right-click on the state you want to transition from and choose the Make Transition option, and then select the state you already have a transition to. A multi-transition is marked with three arrows instead of one. If the conditions of any of the transitions are met, the transition will occur. You can use it as logical OR for transition conditions.
  • If you have more than one transition between states, you can only edit one of them at a time. To edit a transition, select it in the Transitions section of the Inspector.
  • If you want to remove a transition, select it in the Inspector and click on the minus icon, or select it in the Animator Controller and press Delete on the keyboard. Pressing Delete removes all the transitions.
  • If you want to remove a condition from a transition, select it in the Inspector tab and click on the minus icon. To select a condition, you need to click on the handle to the left of the condition drop-down list (the handle looks like a = sign).
  • If you want to remove a parameter from the Animator Controller, you need to click on the handle on the left of the parameter and press the Delete button on the keyboard. You can also right-click on the parameter and choose the Delete option from the context menu.

Using animations from multiple assets

At times it is very convenient to separate animations to multiple assets. A common scenario is to have rigged models separated from animations or different animation types separated from each other (combat from movement, movement from actions, actions from cut scenes, and so on). This recipe shows how to do it for both Humanoid and Generic rigs.

Getting ready

Before we start, you should prepare and import at least two assets containing animations. If you are using a Generic rig, make sure to have the same rig in both assets. You can also use the provided example Unity project and go to the Chapter 01 Working with animations\Recipe 06 Using animations from multiple assets. There is a scene called Example.unity file there. In the scene Hierarchy you can find a Character game object. It has an attached Animator Controller in which you can find two animations: Idle and Wave. In the Rigs directory, you will find the Character.fbx asset containing only a rigged character along with the Idle.fbx and Wave.fbx assets containing the corresponding animations.

If you are exporting FBX files from Blender, make sure to disable the Add Leaf Bones option in the exporter. If you are exporting just the rig and animations (without a mesh), add an empty object to the scene. If you will not do this, your rig could be messed up a bit after import.

How to do it...

To use animations from multiple assets, you need to follow these steps:

  1. Import the files to Unity.
  2. If you are using the Generic rig, you have to set the Avatar Definition to Create From This Model on your character (or reference character if you plan to have multiple characters with the same rig). For each imported animation asset, set the Avatar Definition to Copy From Other Avatar and choose the avatar of your character or reference character. To do so, you need to unfold the character asset, find the avatar, and drag and drop it to the Source field in the Inspector tab.
  1. If you are using a Humanoid rig, you don't have to copy the Avatar Definition (you still can if your rigs are exactly the same; that way you will have fewer avatars in your project, making it easier to find the ones you need).
  2. Create or open an Animator Controller.
  3. Assign animations from different files and build transitions between them.
  4. Run the game to see the animations work.

How it works...

All Generic rigs can use animations from multiple assets that share the same Avatar Definition. To share the same Avatar DefinitionGeneric rigs have to have exactly the same rigs (the same hierarchy, the same bone names and transforms). All Humanoid rigs can use animations from multiple assets that are also set to Humanoid. Additionally, they don't need to have the same rigs because Unity automatically retargets all humanoid animations.

Looping, mirroring and offsetting the animations

Unity allows editing the animations to some extent after they're imported. It can save a lot of work and greatly speed up your workflow.

Getting ready

Before we start, you should prepare and import a Humanoid rig with at least one animation. You can also use the provided example Unity project and go to the Chapter 01 Working with animations\Recipe 07 Looping mirroring and offsetting animations directory. There is a scene called Example.file there. In the scene Hierarchy, you can find a Mirror game object. It has an attached Animator Controller in which you can find two animations: Wave and WaveMirror. In the Rigs directory, you will find the Mirror.fbx asset. If you select it and go to the Inspector, and to the Animations tab, you can find normal and mirrored animation examples, as well as looped animation examples (Idle and IdleMirror).

How to do it...

To set an animation to loop, you need to go through the following steps:

  1. Select the animated asset and go to the Animations tab.
  2. Check the Loop Time checkbox and click on the Apply button. The animation is looped.
  3. If your animation's first and last frames don't match perfectly, you can force them to match with the Loop Pose checkbox. It is not recommended to use this option for animations that have matching first and last frames.

To offset an animation, you need to go through the following steps:

  1. Select the animated asset and go to the Animations tab.
  2. Select your animation and make it loop (Loop Time checkbox).
  3. Enter a value in the Cycle Offset field, below the Loop Pose checkbox.
  4. Click on the Apply button.

To mirror an animation, you need to go through the following steps:

  1. Select the animated Humanoid asset and go to the Animations tab.
  2. Find the Mirror checkbox on the bottom of the animation settings.
  3. Check the Mirror checkbox and click on the Apply button. The animation is mirrored.
  4. Mirroring animations works only for Humanoid rigs.

How it works...

  • Looping animations: This is a common technique used for all cyclic movements (walk and run cycles, idle animations, and so on). If you don't set an animation to loop, it will play once and freeze on the last frame.
  • Offsetting animations: Sometimes it is convenient to offset the cycle of a looped animation. It is often used with the Mirror option for steering animations (clips used to turn the character while moving). We will be showing that in the Using root motion to steer a character recipe in Chapter 4Character Movement.
  • Mirroring animations: This option works only with Humanoid rigs. It is used to flip the animation left to right and can save up to 50 percent of steering animations when combined with the Offset Cycle option.

There's more...

You can also mirror and offset animation states in the Animator Controller. If you select an animation state and go to the Inspector tab, you can find the Mirror and Cycle Offset options. There is also an option to use Animator Controller parameters to switch the Mirror option on and off and set the Cycle Offset. You need to have a Boolean parameter defined for the Mirror option and a float parameter for the Cycle Offset. Those settings will be automatically synchronized with the parameters. Whenever you change a parameter value, the setting will also be changed.

Adjusting the playback speed of animations

Unity allows you to slow down and speed the animation playback in the Animator Controller. You can do it in runtime with scripts to achieve interesting effects, for instance, slow motion.

Getting ready

Before we start, you should prepare and import a rig with at least one animation and create an Animator Controller with at least one animation state for it. You can also use the provided example Unity project and go to the Chapter 01 Working with animations\Recipe 08 Adjusting the playback speed of animationsdirectory. There is a scene called Example.unity there. In the scene Hierarchy, you can find and AdjustSpeed game object. It has an attached Animator Controller in which you can find two animation states: WaveSpeedNormal and WaveSpeedIncreased. There is also an AdjustSpeedByScript game object in the scene. You can increase the playback speed of its animations by pressing the Space button on your keyboard in runtime.

How to do it...

To change the animation playback speed, follow these steps:

  1. Open an Animator Controller.
  2. Select an animation state.
  3. Go to the animation state Inspector and find the Speed parameter below the Motion field.
  4. Enter a number in the Speed parameter to change the playback speed.

How it works...

The Speed parameter set for an animation state in the Animator Controller multiplies the speed playback of the animation state. Setting this parameter to zero will freeze the animation.

There's more...

You can also set the parameter using scripts. Following is an example script (it is used by the AdjustSpeedByScript game object in the provided Example.unity). You can assign it to your animated game object that has the Animator component and an Animator Controller attached:

using UnityEngine; 
using System.Collections; 
 
public class AdjustSpeedByScript : MonoBehaviour { 
//This is a variable, in which we store the reference to the 
Animator component 
private Animator anim; 
//We store the wanted animation speed in this variable, the 
default value is 2 (200%). 
 
public float newAnimationSpeed = 2f; 
void Start () { 
//At the start of the game we assign the Animator 
component to our anim variable 
anim = GetComponent<Animator>(); 
} 
void Update () { 
//We check if player pressed the Space button 
if (Input.GetKeyDown(KeyCode.Space)) { 
//And set the playback speed of the whole Animator 
Controller (it multiplies all states animation 
playback speed) 
 
anim.speed = newAnimationSpeed; 
} 
} 
} 

If you want to change the speed of just one animation state, then add a float parameter to your Animator Controller, use this parameter in the Multiplier field in the animation state Inspector, and change the parameter with scripts using the following function:

anim.SetFloat(string name, float value); 

Here name is the name of your parameter in the Animator Controller and value is the float value you want to set the parameter and playback speed to.

Using override animator controllers to animate different types of characters

If you have multiple types of character in your game, most probably you would like to be able to share the animation states logic between them and just replace the animation clips. Imagine that you have several types of enemies, and their combat logic is the same (they have attacks, movement, hit reactions, and so on) but they use different animation clips. For such situations, Override Animator Controllers come in handy.

Getting ready

You should have at least two characters with different animation clips ready and imported into Unity. You can also download the provided example Unity project and go to the Chapter 01 Working with animations\Recipe 09 Using override animator controllers to animate different types of characters directory. There is a scene called Example.unity there. If you open it, you'll find Warrior and Spider game objects in the Hierarchy. They have Override Animator Controllers attached, and you can examine them. If you run the game, the characters will play attack animations. The underlying logic is defined in the HumanCombat controller (found in the Animator Controllers directory). The Warrior game object uses the HumanCombat controller without overriding it, the Spider game object uses a SpiderCombat override controller.

How to do it...

To use Override Animator Controllers, follow these steps:

  1. Create a normal Animator Controller that will be used as the reference controller containing the logic of animation states. In the provided example, it is the HumanCombat controller, created with Warrior animations.
  2. You can attach this controller to your first character (its Animator component) and use it as previously.
  3. Create an Override Animator Controller by right-clicking on the Project View and choosing CreateOverride Animator Controller.
  4. Select the newly created override controller and go to the Inspector tab.
  5. Drag and drop your original/reference Animator Controller to the Controller field of the newly created override controller.
  6. You will see all your original animation clips listed on the left and fields for overriding those animation clips.
  1. Drag and drop the animation clips from your second character to the override fields corresponding with original animation clips of your first character. In the provided example, Human animations are replaced with Spider animations.
  2. Assign the Override Animator Controller to the Controller field of the Animator component of your second character.

How it works...

Override Animator Controller only replace animation clips from your original Animator Controller. The logic of the original controller stays the same (so you can also use the same scripts to set the same parameters and so on). It is extremely useful for creating NPC characters in your games. You create the Animator Controller once, you write the scripts driving the controller once and only change the animations.

Your original Animator Controller has to have animation clips. You cannot override empty animation states.

Importing object animation from a 3D package

In Unity, you can import not only skeletal animation but also object transform animation. It can be useful for creating complex movements, for instance, an object following a path.

Getting ready

You have to animate an object's translation, rotation, or scale in a 3D package, then export the object as FBX file. You can also download the provided example Unity project and go to the Chapter 01 Working with animations\Recipe 10 Importing object animation from a 3D package directory. There is a scene called Example.unity there. This object has a follow path animation created in Blender and exported to FBX file. It has a normal Animator Controller with that animation as default state (looped). You can run the game to see the object animate.

How to do it...

To import object animation, follow these steps:

  1. Animate an object in a 3D package (translation, rotation, and scale animations are supported).
  2. Import the object into Unity and select the Generic rig type.
  3. You can adjust animation settings normally (loop an animation for instance).
  4. Create an Animator Controller and drag and drop one of the imported animations into the Animator window to create a default animation state.
  5. Place your animated object into a scene and assign the controller to the Animator component of the object.
  6. If you run the game, the object will be animated.

How it works...

Unity imports translation, rotation, and scale animation of 3D objects from a 3D package. It makes it easy to create complex animations and use advanced features of a chosen 3D software. Make sure to bake your animations into frames before importing them to Unity (Blender bakes the exported animations to frames by default). Importing mesh animation (vertices movement) is not supported (you have to use Blend Shapes instead; we will discuss them in detail in the Animating facial expressions with Blend Shapes recipe in Chapter 5Character Actions and Expressions).

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • A straightforward and easy-to-follow format.
  • A selection of the most important tasks
  • and problems.
  • Carefully organized instructions to solve problems efficiently.
  • Clear explanations of what you did.
  • Solutions that can be applied to solve
  • real-world problems.

Description

This recipe-based practical guide will show you how to unleash the power of animation in Unity 5.x and make your games visually impeccable. Our primary focus is on showing you tools and techniques to animate not only humanoid biped characters, but also other elements. This includes non-humanoid character animation, game world creation, UI element animation, and other key features such as opening doors, changing lights, transitioning to different scenes, using physics, setting up ragdolls, creating destructible objects and more. While discussing these topics, the book will focus on mecanim, the Unity 3D animation tool, and how you can use it to perform all these tasks efficiently and quickly. It contains a downloadable Unity project with interactive examples for all the recipes. By the end of this book, you will be confident and self-sufficient in animating your Unity 3D games efficiently.

Who is this book for?

This book is for Unity developers who have some exposure to Unity game development who want to learn the nuances of animation in Unity. Previous knowledge of animation techniques and mecanim is not necessary.

What you will learn

  • Importing animations to Unity
  • Work with different animation assets
  • and components
  • Create, visualize, and edit animated creatures
  • Animating game cut scenes
  • Design character actions and expressions
  • Create gameplay by animating characters and environments
  • Use animations to drive in-game logic

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 27, 2016
Length: 328 pages
Edition : 1st
Language : English
ISBN-13 : 9781785883910
Vendor :
Unity Technologies
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. £16.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : May 27, 2016
Length: 328 pages
Edition : 1st
Language : English
ISBN-13 : 9781785883910
Vendor :
Unity Technologies
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
£16.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
£169.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts
£234.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total £ 115.97
Unity 5.x Game AI Programming Cookbook
£36.99
Unity 5.x Animation Cookbook
£36.99
Unity 5.x Shaders and Effects Cookbook
£41.99
Total £ 115.97 Stars icon

Table of Contents

10 Chapters
Working with Animations Chevron down icon Chevron up icon
Working with the Animation View Chevron down icon Chevron up icon
2D and User Interface Animation Chevron down icon Chevron up icon
Character Movement Chevron down icon Chevron up icon
Character Actions and Expressions Chevron down icon Chevron up icon
Handling Combat Chevron down icon Chevron up icon
Special Effects Chevron down icon Chevron up icon
Animating Cutscenes Chevron down icon Chevron up icon
Physics and Animations Chevron down icon Chevron up icon
Miscellaneous Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(4 Ratings)
5 star 75%
4 star 0%
3 star 0%
2 star 0%
1 star 25%
Ali Apr 15, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
True to what it says on the cover. Basically this is the missing manual that Unity should have provided. All the practical details that you need to get your animations going.
Amazon Verified review Amazon
M. Fischer Jun 02, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
There is some documentation out there on mecanim and the animation tools, BUT most of them seem to be missing so many things compared to this book.And as an already davanced unity useryou search for indepth information and you can't find it on youTube or in the Unity documentaion..This book finally has it !!!!!!!It explains you the basics very well as well as things that will make your work faster and easier.Always showing it on practical exampels or recepies ;)Totally can suggest this book to every animator that also integrates their animations into unityI simply can say - buy it and have _so_ much more fun with the animation tools in Unity.- Animator Override Controller- UI Graphics and mecanim usage- Rigid Body character movement- A lot about controlling the charatcers root motion- many exampels for using triggers- and sooo much more
Amazon Verified review Amazon
Mohan Krishna Dec 15, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Lots of information in the book it's use full for beginners like me
Amazon Verified review Amazon
Carlo R. Montoya Jun 25, 2017
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
I'm using Unity 5.5.0f3 and I gave up after reaching Recipe 03 in Chapter 1. I'm sure these worked in the Unity version the author used but there are just too many errors in the new version to disrupt learning. It would be better if the content is online and updated to sync with Unity's latest version.Good thing I ordered a Kindle version and 'returned' it for a refund.This review is not about the author but rather the sad fact that Unity's engine changes so fast that code written a year ago is not guaranteed to work smoothly today.If you're using the same version the author used, I'm sure you'd have a smoother time learning about Unity animation. In my case, I have to look elsewhere.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.