javascript yield waitforseconds() not working/returning

I have the following code in a player object:

function Start () 
{
    GUI = GameObject.FindWithTag("GUI").GetComponent(InGameGUI);
}

function OnCollisionEnter(hitInfo : Collision)
{
    if(hitInfo.relativeVelocity.magnitude >= 2) //if we hit it too hard, explode!
    { 
        Explode();
    }
}

function Explode() //Drop in a random explosion effect, and destroy ship
{
    var randomNumber : int = Random.Range(0,shipExplosions.length);
    Instantiate(shipExplosions[randomNumber], transform.position, transform.rotation);
    Destroy(gameObject);

    GUI.Lose();
}

And my GUI.Lose() function looks like this (this is my GUI game object, separate game object from above):

function Lose()
{
    print("before yield");
    yield WaitForSeconds(3);
    print("after yield");
    Time.timeScale = 0;
    guiMode = "Lose";
}

When the explode function is called, the loose function is called and I see the message “before yield” print out. I wait three seconds, but I never see the “after yield” message.

If I take the yield out, the function works as I would expect minus the waiting for 3 seconds.

This is on Unity 4. This code is directly from a tutorial that I believe was created on Unity 3.5. I assume the code worked in Unity 3.5 because there are no comments on the sites asking why the yield isn’t working.

What stupid thing am I am doing wrong?

Because you destroyed object. You say:

  1. Destroy(gameObject);
  2. It goes to Lose();
  3. Running Lose until yield.
  4. gameObject destroyed.
  5. Lose function is not valid anymore.

The destroyed game object is the player object. The Lose function exists in my GUI object. I should have been more clear (and I will edit this), they are two separate game objects. The GUI object is not destroyed. In fact, if I remove the destroy(gameObject) it still doesn’t work.

You should call GUI.Lose(); this way: StartCoroutine(GUI.Lose());

Just tried. No go. :*(

It might be also a problem that you are using GUI as your own class, it might not work since there is GUI defined already by Unity.

Ok, i will play around a little more. I didn’t write any of those code. I notice it works on Unity 3.5 but no on Unity 4, so I wondered if there was some change that would have done this.

Like I said, The Lose() function is called. I see the printed message “before yield” but never get the “after yield” one.

Not in Unityscript; StartCoroutine is implicit.

There’s nothing in that code that would be any different in Unity 4 vs Unity 3.

–Eric

Please rename your declaration of GUI to something else, its bad to hide underlying classes with your own variables without good reason.