Search code examples
unity-game-engineunityscript

Unityscript transfer boolean value between functions


I'm having a bit of trouble with some Unityscript.

What I want to do is have a GUI message appear when certain objects are touched (then vanish after a time). I think I have it mostly worked out, but the message trips automatically.

My attempted solution is to have a conditional part of the GUI message that only allows it to appear when a boolean is true. Then in a different script that is already tripped when the object is touched, the boolean is set to true, so the script can run, and reset the boolean to false.

However I'm getting a "You can only call GUI functions from inside OnGUI. I'm not sure what that means.

Message code:

youdied.js
static var deathMessageShow : boolean = false;

function OnGUI() {
if(deathMessageShow == true){
    if(Time.time >= 5 )
        GUI.Box(Rect(200,300,275,150),"You Died");
    }
deathMessageShow = false;
}

Other code (truncated):

dead.js
function OnTriggerEnter()
{
//code that resets environment
youdied.deathMessageShow = true;
}

Any suggestions on what is going on, or a better solution would be greatly appreciated.


Solution

  • The following code will show GUI message for 5 seconds then hides it:

    youdied.js
    static var deathMessageShow : boolean = false;
    
    function OnGUI()
    {
        if(deathMessageShow)
        {
            GUI.Box(Rect(200,300,275,150),"You Died");
    
            // call the function HideDeathMessage() after five seconds
            Invoke("HideDeathMessage", 5.0f);
        }
    }
    
    function HideDeathMessage()
    {
        deathMessageShow = false;
    }
    

    Other code:

    dead.js
    function OnTriggerEnter()
    {
        //code that resets environment
        youdied.deathMessageShow = true;
    }