- Home /
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: http://answers.unity3d.com/questions/787605/mecanim-equvalent-of-animationstop.html
How to solve this? Thanks!
Answer by Sun-Pengfei · Nov 23, 2015 at 10:13 AM
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().
Answer by OctoMan · Nov 22, 2015 at 06:25 PM
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.
Thanks for your advice. Actually I've tried this, but it doesn't work if you call Play("attack") right after Play("idle"). I've worked out a way that'll work, but feels kind of "hack". I'll post my code later.