- Home /
Unity2D - How do you restart/interrupt an animation?
Hey everyone,
So, I'm back to Unity and am playing around with the new built-it 2D features. They seem quite wonderful!
Currently, I'm playing around with the 2D animator graph feature where you use the visual finite state machine window to link together animations.
I have this very simple animation tree:
Basically, it's just a tank where I want the turret to move back when you shoot which I've already sorted out. Currently, to transition from idle to shoot, it's simply a bool called "Attack" that I have to set to true. For the "shoot" state to transition back to "idle", it just plays on the exit time condition right now.
As a simple test, I have this logic to start the fire animation when you fire the turret:
if (Input.GetKeyDown(KeyCode.Space))
{
GetComponent<Animator>().SetBool("Attack", true);
}
Now, the problem is that if I spam the space button, it will still play the entire animation to the end before it wants to replay it. What I want to do is have the ability to "interrupt" the animation if the player fires another bullet in the middle of the current fire animation. In that case, it should simply restart the animation. I haven't been able to figure out the way to do this yet. How would this be done?
Answer by Reeceg · Aug 01, 2014 at 01:39 AM
if (animation.IsPlaying("animation") && Input.GetKeyDown(KeyCode.Space))
{
animation["animation"].time = 0;
yield
GetComponent<Animator>().SetBool("Attack", true);
}
Answer by RedSuinit · Aug 01, 2014 at 02:33 AM
Perhaps try adding this line to your code.
if (Input.GetKeyDown(KeyCode.Space))
{
GetComponent<Animator>().SetBool("Attack", false);
GetComponent<Animator>().SetBool("Attack", true);
}
This way the variable attack will be false then true immediately afterwards, thus stopping, then restarting the animation.
Unfortunately I already tried this, and it didn't work :(
Never $$anonymous$$d I'm a moron who can't read apparently. The issue with my method is that you are using exit time for the condition to end the animation. It looks to me though that Reecegs answer should do what you want.
Or you can add another transition, if you add a transition from any state to idle that is solely based on attack being false that would do what you want with the code that I provided.