- Home /
Pause, Unpause
Okay, so I want to be able to pause and unpause my game (not using a GUI text, but instead by just pressing P) and here is my coding so far...
using UnityEngine;
using System.Collections;
public class Pause : MonoBehaviour {
public bool paused = false;
void Start ()
{
paused = false;
Time.timeScale = .1f;
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown ("p") && paused == false)
{
Time.timeScale = 0;
paused = true;
}
if (Input.GetKeyDown ("p") && paused == true)
{
Time.timeScale = 1;
paused = false;
}
}
}
btw it's in C#. It won't pause but when I hit the P button it goes from Time.timeScale = .1f; to Time.timeScale = 1;
How do I fix that (relativley new to this and I can't find the answer anywhere, trust me.)
Answer by Graham-Dunnett · May 08, 2014 at 08:11 PM
So think about it. To begin you have paused
set to false
. When you press the p key, your test at line 14 will pass, so you'll set paused
to true
. Then, at line 19, you test if the p key is pressed (it was) and if paused
is true
(it is). So you'll always set paused
to false
if the p key is pressed. So, at line 19 do an else if
.
And if you want to trim the code a bit :
if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.P))
{
paused = !paused ;
Time.timeScale = paused ? 0 : 1 ;
}
Yeah, hahah I realized this after I posted the question. I felt like an idiot hahah
Your answer
Follow this Question
Related Questions
Problem changing TimeScale 1 Answer
Pause menu... Isn't pausing everything... 1 Answer
How to Appease a pause menu in a game that changes it's time scale? 1 Answer
TimeScale = 0 crashes Unity 1 Answer
How to Pause game 1 Answer