- Home /
IEnumerator problem
So, my problem is that when I use IEnumerator and i try to increase or decreases by one a variable the variable increases by 7 or 10, the IEnumerator script:
//I use this to call the coroutine
if(Input.GetKey(KeyCode.R) && mags > 0 && magBullets < 30) {
StartCoroutine(Reload());
}
//The IEnumerator
IEnumerator Reload() {
weaponAnimationHolder.clip = reloadAnim;
weaponAnimationHolder.Play(); // don't look to this one, it is just to play an animation
yield return new WaitForSeconds(3f); //wait for 3 seconds
magBullets = maxMagBullets; //all correct here
mags -= 1; // here is the problem, the variable "mags" decreases by 7 or 10
}
The "mags" variable is an int
yes! all the ienumerator works fine but, the "mags -= 1" decreases by 7 ins$$anonymous$$d of 1
Simply use Invoke() for timers in Unity, don't generally use coroutines
Answer by clunk47 · Oct 09, 2013 at 04:23 PM
If you are using your if() statement in Update, the reason you're getting multiple subtractions from mags is because you're using GetKey instead of GetKeyDown. GetKey registers each frame that the key is down. If you're getting 60 fps, it will register 60 times per second... Use GetKeyDown:
if(Input.GetKeyDown(KeyCode.R) && mags > 0 && magBullets < 30) { StartCoroutine(Reload()); }
Your answer
![](https://koobas.hobune.stream/wayback/20220613115620im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Calling IEnumerators 1 Answer
WaitForSeconds not working in iOS only 0 Answers
Pass a function(float) as variable 2 Answers
Can't get past WaitForSeconds in my coroutine 1 Answer
How to stop coroutines, when paused 2 Answers