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.
Adjusting the playback speed of animations
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:
- Open an Animator Controller.
- Select an animation state.
- Go to the animation state Inspector and find the Speed parameter below the Motion field.
- 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.