- Home /
Question by
BrainUK · Jun 20, 2021 at 09:28 PM ·
unity 5javascriptpause game
How do I unpause my game using Time.timeScale?
I'm trying to write a pause script and I can't figure out how to unpause properly. Can anybody help? Here's what I have but it's not working:
#pragma strict
var gamePaused : boolean = false;
function PauseGame() {
if(gamePaused == false && Input.GetKeyDown(KeyCode.Escape) == true || Input.GetButtonDown("Start")) {
Time.timeScale = 0;
gamePaused = true;
}
}
function UnPauseGame() {
if (gamePaused == true && Input.GetKeyDown(KeyCode.Escape) == true || Input.GetButtonDown("Start")) {
Time.timeScale = 1;
gamePaused = false;
}
}
function Update() {
PauseGame();
UnPauseGame();
}
Comment
Best Answer
Answer by BrainUK · Jun 20, 2021 at 09:46 PM
Never mind. I think I've got it:
#pragma strict
var gamePaused : boolean = false;
function Update() {
if(Input.GetKeyDown(KeyCode.Escape) == true || Input.GetButtonDown("Start") == true) {
gamePaused = !gamePaused;
if (gamePaused == true) {
Time.timeScale = 0;
}
else {
Time.timeScale = 1;
}
}
}
Since you already accepted you own anser I wont worry about adding this as an answer only a comment, but you were on the right track in your first bit of code only that you really shouldnt be looking for keydown event in a method other than Update as it will rarely ever detect that the button was pressed, to keep your update function clean and otimised you could try the below code:
function PauseGame() {
Time.timeScale = 0;
}
function UnPauseGame() {
Time.timeScale = 1;
}
function Update() {
if(Input.GetKeyDown(KeyCode.Escape) == true || Input.GetButtonDown("Start") == true) {
gamePaused = !gamePaused;
if(gamePaused) {
PauseGame();
}
else {
UnPauseGame();
}
}
}
Using this you can then add all your paused UI elements to enable/disable inside the Pause/UnPause methods rather than inside the Update function