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:
alt text

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?

if (animation.IsPlaying(“animation”) && Input.GetKeyDown(KeyCode.Space))
{
animation[“animation”].time = 0;
yield
GetComponent().SetBool(“Attack”, true);
}

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.