- Home /
The question is answered, right answer was accepted
Can't set Time.timeScale back to 1.
I am trying to make a platform runner in 3D and wanted to be able to pause the game when the user pressed "P". I was able to do this but now I'm having a problem with resuming the game. I tried setting the Time.timeScale back to 1, but it didn't work. I'm using this code: using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public bool paused = false;
void Pause()
{
Time.timeScale = 0;
}
void Update()
{
if(Input.GetKey("p"))
{
if(paused == false)
{
Pause();
}else
{
paused = false;
Time.timeScale = 1;
}
}
while(paused)
{
Pause();
}
}
}
I have tried to disable the forces on the Rigidbody, but I had the same problem.
I hope someone can help me and thanks in advance.
Answer by hameed-ullah-jan · Apr 11, 2019 at 02:34 PM
Try this simple code, use P for pause and resume both:
bool pause = false;
void Update(){
if(Input.GetKeyDown(KeyCode.P)){
pause = !pause;
if(pause){
Time.timescale = 0;
}else if(!pause){
Time.timescale = 1;
}
}
}
Answer by Bonfire-Boy · Apr 11, 2019 at 03:08 PM
First: You never set paused
to true. So it never goes into the else
clause at line 15.
Solution: set paused
to true in your Pause() function.
Second: once you have code that sets paused
to true, you need to remove the while
block at lines 21-24 entirely, because
a) it's pointless - you only need to call Pause() once
and
b) it's an infinite loop that will make Unity hang and currently you're only getting away with it because you never set paused
to true
Follow this Question
Related Questions
Pause, Unpause 1 Answer
Distribute terrain in zones 3 Answers
Time.timeScale doesnt work with GUI? 0 Answers
Dramatic Camera effect with all physical gameobjects paused? 0 Answers
wait 3 seconds then resume c# 3 Answers