How to trigger the same animator state in unity5 with script?

Example:

In an animator there’re two states: idle, attack.

In animation transition settings:

Default → idle

attack(has exit time of 1) → idle

Goal:

I want to play the attack animation whenever mouse is clicked.

Problem:

Using animator.Play(“attack”); will trigger the attack state successfully, however when I clicked mouse immediately, if the animation in attack state has not finished, it won’t be triggered again.

I searched for some time, only found this: mecanim equvalent of animation.stop() - Questions & Answers - Unity Discussions

How to solve this? Thanks!

One idea to solve this is to call Play(“idle”) before Play(“attack”). The state would transit into idle then immediately transit into attack. However the following piece of code doesn’t work.

public void PlayAttackAnimation()
{
    animator.Play("idle");
    animator.Play("attack");
}

I’ve worked a way to let it work.

bool playAttack = false;

public void PlayAttackAnimation()
{
    animator.Play("idle");
    attackAnimFlag = true;
}

void LateUpdate()
{
    if (attackAnimFlag)
    {
        attackAnimaFlag = false;
        animator.Play("attack");
    }
}

This works in Unity 5.2.2f1, but feels kind of hack.
Notice: It only works using LateUpdate(), if you change the second part as Update(), it won’t work. I don’t know why, guessing Unity must have done some thing related with animator state changing between Update() and LateUpdate().

You want to trigger an animation, even if it’s not ended before? It wouldn’t look good but i would try to trigger to idle, and get rid of exit time,so trigger to exit the running animation. Also use an animtion event in the last frame of your animation to trigger to idle too.