OnGUI coroutine issue

Hey all. I’m trying to make a script for the intro to my game so when the Player walks through a trigger, GUI Text appears, then fades away. I have one script that makes it appear ontriggerenter, and I have one that fades. However, the one that fades activates when the game starts. I drew up this script to try and use both features to suit my need. However I encountered a problem. I get a console error saying that onGUI cannot be declared as a coroutine. How can I fix this?

var lightGameObject : GameObject;

function Start() {
	lightGameObject.enabled = false;
}

function Update() {
	if(Input.GetMouseButtonDown(0))
	{
		lightGameObject.enabled = true;
		yield WaitForSeconds(1);
		lightGameObject.enabled = false;
}
}

The error : OnGUI() can not be a coroutine.

First, you must be getting the error you describe from another script, because there is no OnGUI() in this script. But callbacks that can get called every frame cannot have a ‘yield’ in them. This includes Update(), FixedUpate(), LateUpdate(), OnGUI, OnMouseDrag()…

The fix is to put them in a separate function:

var lightGameObject : GameObject;
 
function Start() {
    lightGameObject.enabled = false;
}
 
function Update() {
    if(Input.GetMouseButtonDown(0)) {
        Toggle();
    }
}

function Toggle() {
    lightGameObject.enabled = true;
    yield WaitForSeconds(1);
    lightGameObject.enabled = false;
}

Note that you may want to do some additional work to prevent Toggle from being called again while it is executing. Right now, if the user hit the mouse button more than once per 1.0 second, multiple Toggle() coroutines will be launched.