Why does unity subtract ammunition per frame?
I'm making an FPS game but I want there to be limited ammo (probably only 2 reloads). My problem now is that Unity subtracts ammunition per frame everytime I do inventoryAmmo -= currentAmmo or inventoryAmmo = inventoryAmmo - currentAmmo so I get negative values.
Here is some code for reference:
if (Input.GetKey(KeyCode.R) && currentAmmo < maxAmmo && inventoryAmmo > 0)
{
StartCoroutine(Reload());
reloading = reloadTime;
}
if(Input.GetMouseButton(0) && currentAmmo <= 0 && inventoryAmmo > 0)
{
StartCoroutine(Reload());
reloading = reloadTime;
}
}
IEnumerator Reload()
{
isReloading = true;
reloadAnim.SetBool("isReloading", true);
yield return new WaitForSeconds(reloadTime);
currentAmmo = maxAmmo;
isReloading = false;
inventoryAmmo = inventoryAmmo - currentAmmo;
reloadAnim.SetBool("isReloading", false);
}
Answer by Kaemcosi · Jun 07, 2021 at 03:51 AM
I can't tell from your code snippet, but i'm assuming you're checking for your input (R-key or left mouse button) in your Update() method. That means you're checking it every frame, and so you'll be starting your reload coroutine every frame, as long as one or both of the keys is pressed.
You should probably only start this coroutine if you're not already reloading, so check for your IsReloading bool in your if-statements.