Escape menu script problem

The script I’ve made here is for an in-game escape menu, it has 2 buttons, Resume and Quit, quit leads to the main menu and resume un-pauses the game. When you first hit escape it disables the mouselook script for the player and sets the timescale to 0, when you hit resume it’s supposed to set timescale to 1 and enable the mouselook script again.

Here’s the script:

function Update ()
{
    if(Input.GetKeyDown("escape"))
    {
        if(Time.timeScale == 0)
        {
            Time.timeScale = 1;
        }
        else
        {
            Time.timeScale = 0;
        }
    }
}

function OnGUI()
{
    if(Time.timeScale == 0)
    {
        ButtonGUI();
        script = GetComponent(MouseLook);
        script.enabled = false;
    }
}

function ButtonGUI()
{
    GUI.Label (Rect (100, 25, 200, 60), "PAUSED");
    
    if (GUI.Button (Rect (100, 55, 100, 30), "Resume"))
    {
        Time.timeScale = 1;
        script = GetComponent(MouseLook);
        script.enabled = true;
    }
    
    if (GUI.Button (Rect (100, 95, 100, 30), "Quit"))
    {
        Application.LoadLevel(0);
    }
}

What did I do to make it not work?

Some things that might cause problems:

  • You toggle the timescale when ever you press escape, but you don’t handle the enable / disable of your script at this place.
  • Disabling the script in OnGUI doesn’t make much sense. This will disable the script 2 times per frame…
  • Make sure this script is attached to the same object that contains the Mouselook script or GetComponent will fail. If they should be on different objects, use a public variable to access the mouselook script.

I would do it like this:

var script : MouseLook;


function Start()
{
    // Since there is propably just one MouseLook script, FindObjectsOfType will
    // find the instance no matter to which gameobject it's attacht to.
    / We do it in start because FindObjectsOfType / GetComponent is a slow function
    script = FindObjectsOfType(MouseLook) as MouseLook;
}

function SetPause(state : Boolean)
{
    if (state)  // We want to pause the game
    {
        Time.timeScale = 0.0;
        script.enabled = false;
    }
    else
    {
        Time.timeScale = 1.0;
        script.enabled = true;
    }
}

function Update ()
{
    if(Input.GetKeyDown("escape"))
    {
        SetPause(Time.timeScale == 1.0); // toggle
    }
}

function OnGUI()
{
    if(Time.timeScale == 0)
    {
        ButtonGUI();
    }
}

function ButtonGUI()
{
    GUI.Label (Rect (100, 25, 200, 60), "PAUSED");

    if (GUI.Button (Rect (100, 55, 100, 30), "Resume"))
    {
        SetPause(false); // exit "pause" mode
    }

    if (GUI.Button (Rect (100, 95, 100, 30), "Quit"))
    {
        Application.LoadLevel(0);
    }
}