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.
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();
}
Answer by Landern · Oct 28, 2015 at 01:19 PM
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;
}
Thank you so much! I had to change your statement from:
if(ammo <= 0 && !processingReload)
{
reload = true;
processingReload = true;
}
to:
if(ammo <= 0 && !processingReload)
{
reload = true;
processingReload = false;
}
in order for it to work. But thank you so much for showing me that about how to avoid stacking the Coroutines @Landern!
@Landern ok now for some reason it doesn't work... It worked for a few tries and then I saved the script and exited Unity. Now I opened up Unity and it did the same thing as in the Demonstration Video. Any suggestions?
Your answer
Follow this Question
Related Questions
GetKeyUp does not get called sometimes. 1 Answer
moving object up & down with 1 keycode. 0 Answers
Set Number of Targets based on int Number of Players 1 Answer
How to reseting int ?? 1 Answer