yield WaitForSeconds makes GUI button disappear

I’m showing a button, and when clicked, it plays an audio file. It should wait until the audio finishes playing and then delete another object. But, when I include the yield WaitForSeconds line, the GUI button fails to display.

var audioToPlay1:AudioClip;

function OnGUI() {
	if (GUI.Button(Rect(50,100,300,30),"Play the audio")) {
		audio.clip = audioToPlay1;
		audio.Play();

// THE FOLLOWING LINE MAKES THE BUTTON DISAPPEAR

		yield WaitForSeconds (audio.clip.length);
	
		var objectToClear = GameObject.Find("collision_object");
		Destroy(objectToClear);
		
	}
}

Is there any reason why the inclusion of yield WaitForSeconds would cause the GUI button to disappear? Thanks in advance.

1 Answer

1

You can’t make OnGUI into a coroutine; it runs every frame and can’t be paused or interrupted in any way. You can move the button code into a separate function and have that be a coroutine instead.