- Home /
I am creating a pause button and when I click it the score keeps rising. How can I stop it?
Script:
function Update() { score+=1;
}
function OnGUI() { if(GUI.Button(new Rect(500,500,500,500),"Pause")) { Pause(); }
}
function Pause() {
if(isPaused == true) Time.timeScale = 1; isPaused = false; { Time.timeScale = 1; isPaused = false; }
else { Time.timeScale = 0; isPaused = true; } }
When entering code into your question here on Unity Answers, please use the code formatting button (Ctrl-$$anonymous$$). Otherwise it is quite difficult to read.
Answer by Coderdood · Jun 17, 2013 at 04:07 AM
See this excellent answer for a detailed explanation. But basically a behavior's update method will continue to fire even when Time.timeScale is 0. If you want the code to only run when Time.timeScale is not zero then use FixedUpdate as the documentation here states:
FixedUpdate functions will not be called when timeScale is set to zero
So changing your code to the following should work:
function FixedUpdate()
{
score+=1;
}
function OnGUI()
{
if(GUI.Button(new Rect(500,500,500,500),"Pause")) { Pause(); }
}
function Pause()
{
if(isPaused == true) { Time.timeScale = 1; isPaused = false; }
else { Time.timeScale = 0; isPaused = true; }
}
Just want to mention that you do not have to put:
if (isPaused == true)
You can do it like this:
if (isPaused)
And it's the same thing, but more readable.