- Home /
Instantiating projectiles even while reloading
Hi all, I'm currently working on a rogue-like, top-down 2d shooter game, but I am having trouble with the cooldown mechanism. So far, the player has three ammo that will take 2 seconds to reload once depleting. But, I've noticed that if you spam during the cooldown, many projectiles will suddenly be instantiated after reloading and these do not affect the ammo count at all. Here's my player script:
void Update()
{
//INPUT
ProcessInputs();
//SHOOTING
Shoot();
//UPDATING AMMO TEXT
ammoText.text += " " + ammo.ToString();
}
void Shoot()
{
if (Input.GetKeyDown(KeyCode.Mouse0) && ammo > 0)
{
Instantiate(butterProjectile, transform);
ammo--;
}
else if (ammo == 0)
{
StartCoroutine(Reload());
}
}
IEnumerator Reload()
{
//RELOAD COOLDOWN
yield return new WaitForSeconds(2f);
//BACK TO FULL AMMO :D
ammo = 3;
}
(Sorry I know it's pretty basic code.) I doubt this has anything to do with the projectile script, but I can't seem to find anything wrong in this one. Any help would be most appreciated. Thank you :)
Edit: This issue also occurs after reloading and the ammo count goes all wild when I start spamming my mouse :(
Answer by Arano · Jun 02, 2021 at 08:00 AM
try adding this:
else if (ammo == 0 && !reloading)
{
StartCoroutine(Reload());
reloading = true; //set to false at end of reload
}
right now when ur ammo is 0, the 'reload' function is called 60 frames a second inside update, and at 60 frames a second your gun will reload and keep reloading a few seconds after its filled again
Answer by DenisIsDenis · Jun 02, 2021 at 08:09 AM
In your code, when the bullets run out, reload is activated every frame. A boolean variable must be entered to track the re-start of the recharge:
bool isActiveReload;
void Update()
{
// your Update
}
void Shoot()
{
if (Input.GetKeyDown(KeyCode.Mouse0) && ammo > 0)
{
Instantiate(butterProjectile, transform);
ammo--;
}
else if (ammo == 0 && !isActiveReload)
{
StartCoroutine(Reload());
}
}
IEnumerator Reload()
{
//RELOAD COOLDOWN
isActiveReload = true;
yield return new WaitForSeconds(2f);
//BACK TO FULL AMMO :D
isActiveReload = false;
ammo = 3;
}
Your answer
Follow this Question
Related Questions
Prefab Shooting 0 Answers
Firing a particle effect prefab from your character 1 Answer
Destorying prefab and instanstiating again? 0 Answers
Physics on shooting objects/effects 1 Answer
Disable shooting whilst reloading? 1 Answer