When you use animators and animations in your game, you may want to be able to play an animation even if it’s already running.

To explain how to do this, we will create a scene with a simple square object. This square will have an animator component attached to it.

With transition

You can achieve an animation with transition by playing it with the CrossFade method.

Let’s create a new animation like this one :

animation_with_transition

Add a new C# script component attached to the cube object :

public class MoveBehavior : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {

    }

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

    }

    void OnGUI()
    {
        if (GUI.Button(new Rect(10, 70, 50, 30), "Replay"))
        {
            var animator = GetComponent<Animator>();
            animator.CrossFade("Move", 1f);
        }
    }
}

If you play the scene and click on the “Replay” button, the animation will start.

Notice that if you click on the button again between 0 and 1 second, the animation will start transition, but if you click between 1 and 2 seconds nothing will happen. It’s because our animation during 2 seconds and we set the fading length to 1 second. To be able to play a transition all along the animation, set the fading length to 2 seconds.

Without transition

Unlike the CrossFade method, the Play method will not rewind to the beginning. So, if you want to replay an animation you can use a little trick.

Create your animation in two parts. The first part need to be a one-frame animation :

first_animation_without_transition

The second part is the “real” animation :

second_animation_without_transition

Edit the script with those snippet :

public class MoveBehavior : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {

    }

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

    }

    void OnGUI()
    {
        if (GUI.Button(new Rect(10, 70, 50, 30), "Replay"))
        {
            var animator = GetComponent<Animator>();
            animator.Play("BeginMove");
        }
    }
}

By playing the BeginMove animation, it will transition to the EndMove after only one frame. So, if you play again BeginMove after 1 second, the animator current animation will be EndMove so you will be able to replay the animation to the beginning :)

Have fun !