AmmoScript.cs troubles...

I am having trouble with my “ammo” integer variable. Every time I hit the “R” key to reload, the system works fine. But every time I let the ammo run to 0, it doesn’t work… Any suggestions or links to related questions that have been solved are welcome.

Demonstration Video

Code:

void Update ()
	{
		display.text = ammo.ToString();
		if(Input.GetKeyDown(KeyCode.Mouse0) && gun.canFire && !reload)
		{
			ammo--;
		}
		
		if(ammo <= 0)
		{
			reload = true;
		}
		
		if(reload || Input.GetKeyDown(KeyCode.R))
		{
			StartCoroutine("Reload");
		}
	}
	
	IEnumerator Reload ()
	{
		gun.canFire = false;
		yield return new WaitForSeconds(reloadRate);
		reload = false;
		ammo = ammoCache;
		gun.canFire = true;
		display.text = ammo.ToString();
	}

You keep stacking the Coroutine, update is ran once a frame, it would be suggested you constraint that call with another variable in the script that indicates you’re in the process of reloading. You may also want to consider combining the first two if statements for the mouse and ammo amount check so if they reach 0 by pressing the mouse button it reloads.

// put up where local variables belong in your class.
private bool processingReload = false;

void Update ()
{
	display.text = ammo.ToString();
	
	if(Input.GetKeyDown(KeyCode.Mouse0) && gun.canFire && !reload)
	{
		ammo--;
	}

	// if ammo is less than or equal to 0 and you're not already reloading.
	if(ammo <= 0 && !processingReload)
	{
		reload = true;
		processingReload = true;
	}

	// If either you're automatically reloading or the key 'r' is pressed and you're already not in the processing of reloading, start the Coroutine.
	if((reload || Input.GetKeyDown(KeyCode.R)) && !processingReload)
	{
		StartCoroutine("Reload");
	}
}

IEnumerator Reload ()
{
	gun.canFire = false;
	yield return new WaitForSeconds(reloadRate);
	reload = false;
	ammo = ammoCache;
	gun.canFire = true;
	display.text = ammo.ToString();
	processingReload = false;
}