Wait for animation to finish

I have a animated rifle that I am trying to script into playing correctly. The script I have wrote tells the animation to play if the LMB is clicked, this works but I can rapidly click the button without waiting for the animation to finish. How could I make my gun only play the animation when it is not being played to start with?

This is part of my script:

function Update (){

if(Input.GetButtonDown("Fire1")){

    Shoot();
}

function Shoot () {





if(Input.GetButtonDown("Fire1")){

   if(bulletsLeft > 0 ){

     bulletsLeft -- ;

     animation.Stop();

     animation.Play("shoot");

   }

}

}

Updated 28.10 :slight_smile: Search for differences :slight_smile:

function Start () {

	animation["reload"].speed = 1.8;
	animation["shoot1"].speed = 2.6;
	animation["shoot1"].wrapMode = WrapMode.Once;
	animation["reload"].wrapMode = WrapMode.Once;
	animation["shoot1"].layer = 1;
	animation["reload"].layer = 2;
	animation.Stop();
}

var ableToShoot = true;

function Update ()
{
	if(Input.GetButtonDown("Fire1") && ableToShoot )
     	Shoot();
     	   	
    if(Input.GetKeyDown("r"))
		Reload();
}

	
var fullClip : int = 8;
var bulletsLeft : int = 8;
var waitTime = 1.8;

function Shoot () 
{
	if(bulletsLeft > 0 )
	{
 		ableToShoot = false;
 		bulletsLeft -- ;
 		animation.Stop();
 		animation.Play("shoot1");
	}
}

function OnComplete() { ableToShoot = true; }

function Reload () 
{
		ableToShoot = false;
		animation.CrossFade("reload");
		yield WaitForSeconds(waitTime);
		bulletsLeft = fullClip ;
		ableToShoot = true;
}

Here’s another way to do this. This is the one I use for my game:

GameObject objectToAnimate;

void Start()
{
    objectToAnimate = GameObject.Find("objectName"); // Just in case is an external object
}


void StartAndWaitAnimation(string animationName)
{
   StartCoroutine(PlayAnimationAsync(animationName));
}

IEnumerator PlayAnimationAsync(string animationName)
{
    objectToAnimate.animation[animationName].wrapMode = WrapMode.Once; // choose your wrapping mode
    objectToAnimate.animation.Play();
    yield return new WaitForSeconds(objetToAnimate.animation[animationName].lenght); //This does the magic
    //Do the stuff after the animation ends
    DoOtherStuff();
}

This way you separate your code from your animation design, so the code takes care of the order and execution, instead having lots of triggers on your animations. Just a point of view.

Hope this helps.

function Shoot () {
if(bulletsLeft > 0 && !animation.IsPlaying(“shoot”) ){
ableToShoot = false;
bulletsLeft – ;
animation.Stop();
animation.Play(“shoot”);
}
}