Pause script

Why doesn’t this script pause the game when i’m pressing esc? It only works if I toggle pause so it start paused

var paused=false;

function OnGUI(){
	if( Input.GetKeyDown(KeyCode.Escape) ){
		paused=!paused;
	}
	if(paused){
		if (GUI.Button(Rect(10,10,100,50),"Resume Game"))
			paused=false;
		if (GUI.Button(Rect(10,60,100,50),"Main Menu"))
		Application.LoadLevel(3);
		
		
		// Hide the cursor
		Screen.showCursor = true;
		

		}
	Time.timeScale=paused ? 0.0 : 1.0;
	
}

and why does the fps camera still moves when the game is paused?

I’m new to unity3d scripting, so please help! :smile::smile:

havent messed with pause so i cant assist with pausing your game yet (im new too) - but I did notice your ‘if’ statements lack opening brackets, and perhaps closing brackets

Time.timeScale isn’t a good way to halt a game… I’ve tried it, and got a lot of undesired effects…

Mainly, timeScale works on the physics simulation, so if you’re not relying on physics, you might not get a full pause with it…

The best approach for pausing, is to have a central script handling the pausing, with static variables so every other script can know if the script is going into pause or not.

Then, each script must detect whether the game is paused of not, and not update if it is…

Physics-based objects can go into pause also by flagging themselves as isKinematic. (you will have to back up the velocities of the rigidbody, though)

This is how I did it here… worked a lot better than stopping Time, since I needed a bunch of other stuff to happen while the game was paused.

About your script, I must say I don’t see anything wrong with it… in theory it should work… but as I said, fiddling with timeScale is kinda unpredictable :wink:

Hope this helps

Cheers

I know this is really late answering, but I think it will help other people with the problem. Here.

#Pragma strict

var paused : boolean = false;

function Update(){
//Unity hates it if you don't have an update function.
}

function OnGUI(){

    if(Input.GetKeyDown("escape") ){

        paused = !paused;

    }

    if(paused){

        if (GUI.Button(Rect(10,10,100,50),"Resume Game"))

            paused = false;

        if (GUI.Button(Rect(10,60,100,50),"Main Menu"))

        Application.LoadLevel("Level_Name_Here");

        // Hide the cursor

        Screen.showCursor = true;
        Time.timeScale = 0.0;
        }
        if(!paused) {
        Time.timeScale = 1.0;
         }
//If you put timescale here, Unity doesn't know why you're mentioning it.

}