Firing mechanism not working (C#)

Hey guys!

So I made a script that fires the weapon and the gun does animations and all that jazz. My problem is the script keeps shooting and rapid fire instead of following the pattern of the animation (which is 0.333 seconds long). Any ideas? The script is included below:

IEnumerator FireWeapon ()
{
	Rigidbody pel = Instantiate (bullet, transform.position, transform.rotation) as Rigidbody;
	pel.rigidbody.AddForce (transform.forward * speed);
	ammo--;
	anim.SetBool ("firing", true);
	yield return new WaitForSeconds (0.333f); //length of firing animation
}

Everytime you call StartCoroutine(FireWeapon()); you are creating a new “thread”. That wait doesn’t do anything.

You have two options:

  1. You make a timer in the Update() fuction call the coroutine only if the button is pressed and the timer is 0.
  2. You make an infinite while in the FireWeapon() coroutine and you do the shooting if the button is pressed

Example:

Start(){
   StartCoroutine (FireWeapon());
}

IEnumerator FireWeapon ()
{
   while (1==1){
      if (shouldShoot){ // shouldShoot can be replaced by your Input code
         Rigidbody pel = Instantiate (bullet, transform.position, transform.rotation) as Rigidbody;
         pel.rigidbody.AddForce (transform.forward * speed);
         ammo--;
         anim.SetBool ("firing", true);
         yield return new WaitForSeconds (0.333f);
      }
      yield return 0; // Wait for next frame and continue the loop
   }

}