- Home /
C# yield not working.
I am making a reload time, but when I start a coroutine, it doesn't wait for 3 seconds and then reloads. Here is my code:
void Update(){
if(ammoInClip == 0){
StartCoroutine("reload", 3f);
ammoInClip = 30;
}
}
IEnumerator reload(float wait){
yield return new WaitForSeconds (wait);
}
Hi
Your coroutine waits 3 seconds and nothing more (in a coroutine). So you need to put the ammoInClip inside the coroutine or better delete the coroutine and make the yield before the ammoInClip = 30 line.
if (ammoInClip == 0)
{
yield return new WaitForSeconds(3);
ammoInClip = 30;
}
Hope it helps
I think you don't quite know how Coroutines work...
You need to reload after yielding. The StartCoroutine method doesn't wait, it just starts up a coroutine that waits. But as you have it, the coroutine starts, waits for 3 seconds, and doesn't do anything.
IEnumerator Reload( float wait)
{
yield return new WaitForSeconds( wait );
ammoInClip = 30;
}
Now the coroutine waits, then reloads. Now you need to change the if statement in your Update loop so you aren't firing off tons of coroutines every update for 3 seconds. Just have a isReloading bool that you flip on when you fire and check against before firing.
$$anonymous$$ake sense? Hope this helps!
thank you to Op_toss, your answer help me out of this!
i have the wrong concept about the "yield wait", you just correct me, thanks!
Answer by roberto_sc · Jun 15, 2013 at 12:18 AM
The problem happens because when you yield
, you immediately return the control to the Update
method. It then executes the ammoInClip = 30
. After 3 seconds, the control returns to Reload
- that does nothing.
That's why you have to put ammoInClip = 30
after the yield, so it can return the control to the Update
method, continue the game and come back after 3 seconds to reload.
void Update(){
if(ammoInClip == 0){
StartCoroutine(Reload(3f));
}
}
IEnumerator Reload(float wait){
yield return new WaitForSeconds (wait);
ammoInClip = 30;
}
Note the call for StartCoroutine
, I'm not using a string, better for type-safety.
Do you come from Java? Methods in C# usually starts with lowercase :)
Thanks so much for your help. I just found out about coroutines today lol. Thanks
Answer by umangindianic · Jul 02, 2013 at 06:59 AM
With the use of code and whenever you want to StartCoroutine that has require the method name and its argument if you have passed.
void Update(){
if(ammoInClip == 0){
StartCoroutine(reload(3.0f));
ammoInClip = 30;
}
}
IEnumerator reload(float wait){
yield return new WaitForSeconds (wait);
}
Your answer
Follow this Question
Related Questions
Alternative for semaphores in Unity? 2 Answers
WaitUntil Combined With sqrMagnitude is not working? 1 Answer
C# Coroutine help 1 Answer
Wierd issue with Coroutines? 2 Answers
WaitForSeconds Question 2 Answers