- Home /
WaitForSeconds does not work
My following code just doesn't work proberly and I see no mistake... The gameObject plus should be shown for 0.5 seconds and then disappear again. It apperas, but then does not disapper after 0.5 seconds but stays. What am I doing wrong?
if (health > 0) {
StartCoroutine (show (0.5f));
}
IEnumerator show (float delay) {
plus.SetActive (true);
yield return new WaitForSeconds (delay);
plus.SetActive (false);
yield break;
}
You don't need yield break
, because there is nothing after that command. The co-routine is gonna finish anyways. Try that. Also try setting enabled property to false, if it still doesn't work.
Is that the only code that affects the plus gameObject? Is the coroutine called just once? Use print or Debug.Log lines to make sure of that.
Also, you wrote WaitForSeconds doesn't work but it's really hard to believe. Add a print or Debug.Log line after the WaitForSeconds line to make sure, your problem is probably in some code you didn't share.
Yes it's the only code that affects the plus. I printed a line at the beginning of the IEnumerator and it was printed once. I tried now to print a line after the WaitForSeconds and it was not printed. I know it's hard to believe. I just can't find a mistake, too :(
Answer by tanoshimi · Feb 22, 2015 at 08:22 AM
Is the first snippet of code (where you call StartRoutine) in Update()? If so, unless you then change health
, you're launching multiple coroutines - a new one each frame - and they'll each be setting the state of the same plus
object.
Add some condition to ensure your coroutine is only fired once.
Thanks for your answers! I tried everything but it still won't work. I deleted the yield break and I changed health in the if statement before StartCoroutine. The If statement wehre I call StartCoroutine is in OnTriggerEnter2D (not in Update)... I also tried to enable the sprite renderer ins$$anonymous$$d of the whole gameObject but the result is always the same: the plus appears but does not disappear again.