Search code examples
c#unity-game-enginecoroutinereloading

More bullets spawn than allowed


Not sure why this happens but this code allows for more than 3 bullets to be fired after reloading. Am trying to work out why. I think it may be the time between checking which is this issues but I could be wrong.

Any help would be appreciated.

public bool isFiring;
public bool isReloading = false; 
 public BulletController bullet; // Reference another script
 public float bulletSpeed; // bullet speed
 public float timeBetweenShots; // time between shots can be fired
 private float shotCounter;
 public Transform firePoint;
 public static int ammoRemaining = 3;
 public static int maxAmmo = 3;
 public Transform ammoText;
 // Use this for initialization
 void Awake () {
     isReloading = false;
     ammoRemaining = maxAmmo;
 }

 // Update is called once per frame
 void Update () {
     if(isFiring == true )
     {
         shotCounter -= Time.deltaTime;
         if(shotCounter <= 0 && ammoRemaining > 0 && isReloading == false)
         {
             shotCounter = timeBetweenShots;
             BulletController newBullet = Instantiate(bullet, firePoint.position, firePoint.rotation) as BulletController; // creates a new instance of the bullet
             newBullet.speed = bulletSpeed;
             ammoRemaining -= 1;
             ammoText.GetComponent<Text>().text = "Ammo:" + ammoRemaining;
         }

 }
 else if (ammoRemaining == 0)
 {
     StartCoroutine(Reload());
 }
 else
 {
     shotCounter = 0;
 }
 }
 public IEnumerator Reload()
 {
     isReloading = true;
     ammoText.GetComponent<Text>().text = "REL...";
     yield return new WaitForSeconds(2);
     ammoRemaining = maxAmmo;
     isReloading = false;
     ammoText.GetComponent<Text>().text = "Ammo:" + ammoRemaining;
 }

Solution

  • The issue (as discussed) is that your Reload() coroutine is getting called additional times within Update() after you fire the last shot and before letting go of MouseButton(0). To avoid this, I would suggest checking to make sure you are not already reloading, before starting the coroutine:

     else if (ammoRemaining == 0 && !isReloading)
     {
         StartCoroutine(Reload());
     }