- Home /
WaitForSeconds doesent run properly.
Hello everyone, been looking around and i cant seem to figure out why this problem pops up, so i was hoping some smart person could help me out.
The problem is that the code runs just fine until i reaches WaitForSeconds, it seems that WaitForSeconds doesent run at all leaving my screen green till i change the GUITexture with another function.
Heres the code:
public GUITexture splash;
public Player player;
// Use this for initialization
void Start ()
{
splash.enabled = false;
}
// Update is called once per frame
void Update ()
{
}
void OnTriggerEnter(Collider col)
{
if(col.gameObject.tag == "Player")
{
StartCoroutine(SplashPickUp(0.2f));
player.Armor += 20;
Destroy(gameObject);
}
}
IEnumerator SplashPickUp(float cooldown)
{
splash.enabled = true;
splash.color = Color.green;
yield return new WaitForSeconds(cooldown);
splash.enabled = false;
}
Consider -- learn about Invoke(). it is extremely simple.
learn to use Invoke -- later come back and master coroutines/yield/WaitForSeconds
@fattie - for once that wouldn't have worked either ;)
Answer by whydoidoit · Sep 24, 2012 at 10:14 AM
Your problem is that you are doing a Destroy on the game object after starting the coroutine - therefore the coroutine will never run after the wait as it is dead. Put your Destroy inside the coroutine after the wait or consider starting the coroutine on a game object that won't be destroyed.
Thank you very much, moving the "Destroy(gameObject)" into the IEnumerator worked like a charm.