waiting in gui?

because you can’t yield in the gui this script here below doesn’t do the job. The moment I click the button the other level is loaded and I can’t hear the audio. I want to click the button, the audio plays and than the level gets loaded. Any ideas/help?

function OnGUI(){
  if (GUI.Button (Rect (23,180, 281, 70), "load level"))
  {
    audio.Play();
    yield new WaitForSeconds (10);
    Application.LoadLevel("level1");
  }
}

I can’t confirm the yield prob but a simple hack around based on your description…

function OnGUI(){
if (GUI.Button (Rect (23,180, 281, 70), "load level"))
{
LoadNext();
}
}

function LoadNext()
{
audio.Play();
yield new WaitForSeconds (10);
Application.LoadLevel("level1");
}

OnGUI cannot have yields as it’s being called repeatedly each frame, allowing that would seriously break the UI feature set entirely. The way to do it is as pete noted, use a helper function that can in fact have a yield statement in it and all should be good (and BTW, that is not a “hack around”).

And lesfundi, when posting code in your posts use the Code button, or manually wrap the scripts in a code block ([ code ]…[ /code ], without the spaces) for better formatting. I’ll edit your post so you can see that as an example.

I expected that was the case but couldn’t confirm atm of my post. Still everything in programming is a hack around afaic :smile:
But ok it’s an “intended hack around” :smile:

[Ok ok guys, don’t get confused. This is NOT a workaround. Just the way it’s supposed to be.]