Restart same animation in Mecanim

I’m using Mecanim to handle my animations on my character, which has been great. However, I’ve hit a problem.

I have an attack animation that’s about a second long, and is triggered by a button. In the middle of this animation, if the player presses the same button again, I’d like the attack animation to restart from the beginning. This may be a simple thing, but how might I do that? Mecanim is great at handling transitions from one animation to another, but how would it restart it’s own animation?

dunno, but now you can do just:

Animator.Play(state, layer, normalizedTime);

if you use

Animator.Play("same state you are", -1, 0f);

it will restart current state, if you put whatever float from 0 to 1 into normalized time, you can set it to any time position you want

you can also use

Animator.CrossFade(state, crossFadeTime, layer, normalizedTime);

EDIT: This doesn’t work in Unity 5, as mentioned in the comments.

Just a note, at least in Unity 4.1.5, you can use Animator.ForceStateNormalizedTime which takes in a normalized float (0.0 to 1.0 range) to force the playback position of the currently active state (supposedly won’t work while in transition).

So you can do something like myAnimator.ForceStateNormalizedTime(0.0f) to replay the current animation.

Not totally sure but it sounds like someone from Unity said: “We wont support API control over transition in 4.0. So only in the UI… for now”, so a quick way if it isn’t doable in the code that you can find, you can create a state in the UI and have it transition to the same animation (and maybe back again?) if you set a certain flag.

Actually the most easiest method is to set a Trigger parameter to relaunch the same animation.

GetComponent<Animator> ().SetTrigger ( "Play" );


GetComponent<Animator> ().ResetTrigger ( "Play" );

And setup the Animator like this:

If you’re trying to accomplish something like this from the animation controller state machine instead of from code, you’re going to want to uncheck Has Exit Time and check Can Transition to Self on the transition from Any State to your state.

Hi Screenhog, maybe you can try animator.Play(0) or animator.Play(null), it can restart the current state too.