- Home /
C# WaitForSeconds isn't waiting for any seconds
Hi. I know this question has been asked before, but I'm trying to wait for some seconds and the waiting just isn't happening. The coroutine gets called, and the function after the wait is called, but the wait just doesn't happen.
void Shoot ()
{
if (bulletCount != 0)
{
//the gun shoots, yadda yadda
}
else if (bulletCount == 0)
{
bulletCount = magazineSize;
StartCoroutine(Reload());
}
else
{
Debug.Log("an error happened");
}
}
IEnumerator Reload()
{
Debug.Log("got to reload");
yield return new WaitForSecondsRealtime(5);
Shoot();
}
I'm using realtime because I'm not sure what metric the game's time is using, or whatever with deltatime and all that. But yeah, it recurs through shoot again and prints the debug log, but no waiting actually occurs.
Answer by Geejayz · Apr 24, 2018 at 06:18 PM
Where do you decrease the value of bulletCount? Assumming it is 5 for example right now. What reduces it to zero in order for your "else if" statement to fire?
I believe your issue though may be around the fact that as soon as bulletCount is 0, you reset it to magazineSize. Will your code do what you expect if you move bulletCount = magazineSize into the Reload co-routine?
It decreases bulletcount in the part i deleted during the gun shooting, once per shot.
I just moved the line up into reload and it works!! I assumed it would run through it all before checking again, but I guess not. Thanks a ton!
Answer by tormentoarmagedoom · Apr 24, 2018 at 07:21 AM
Good day.
I don't know why its not working (I've never used it) i normally use the Invoke function, wich aloows to run a methiod in a specific time in seconds
Invoke ("Shoot", 5);
Bye!
I tried using invoke as well, with the same problem -- it calls shoot just fine when the code gets to the invoke line, but it doesn't wait at all.
Avoid calling function or anything if that matter, with strings.