How to program a pause/unpause button in C#.
I'm really new to programming (been at it on and off for about 3 or so weeks) and I'm currently try to program a pause and unpause button for a game. I've looked at a few video's but I'm mostly trying to figure this all out myself and avoid just copying code down so I've mostly written this thing myself. I've been through a couple iterations of this code, all of them allowed me to pause but not unpause. This most recent one allows me to pause sometimes and unpause sometimes. It's very weird, I can tap the pause button and an object stops for a second but if I press it a lot (or simply old the button down) it'll stop completely. It works the exact same way for unapausing, tapping causes it to start for a second while tapping a lot will cause it to start again.
Again, I have no real Idea what I'm doing so you'll have to excuse the most likely mediocre code.
using UnityEngine;
using System.Collections;
public class PauseGame : MonoBehaviour {
bool Pause = false;
void Update()
{
if (Pause == false)
{
Time.timeScale = 1;
}
else
{
Time.timeScale = 0;
}
if (Input.GetKey(KeyCode.P))
{
if (Pause == true)
{
Pause = false;
}
else
{
Pause = true;
}
}
}
}
Answer by hoy_smallfry · Apr 29, 2013 at 08:27 PM
GetKey will trigger every frame that the key is held down. That means that for however many frames you've been holding it down, your Pause variable is alternating between true and false.
Take this an example: Pause starts out false. You've held it down for more than one frame. Lines 24 though 32 of your code will dictate that after the first frame, Pause gets set as true. The second frame, it gets set as false, the third frame creates the same condition as the first frame, again and again.
If you only want the input to trigger the pause the first time it detects the key is down, use Input.GetKeyDown
.
You could probably do away with the Pause value as well and simply change the time scale when the button is pressed, like so:
void Update()
{
if (Input.GetKeyDown(KeyCode.P))
{
if (Time.timeScale == 1)
{
Time.timeScale = 0;
}
else
{
Time.timeScale = 1;
}
}
}
Wow, I can't believe it was that simple, I was really over-complicating it apparently. I think I had tried Get$$anonymous$$eyDown before but something messed up and I went back to Get$$anonymous$$ey. Thanks.
Answer by Numonic · Dec 26, 2017 at 07:50 PM
This was simple and concise especially with me using my Logitech Controller on PC. Thanks!
public void PauseGameFeature()
{
if (Input.GetKeyUp(KeyCode.Joystick1Button9))
{
if(Time.timeScale == 1)
{
Pause();
}
else
{
UnPause();
}
}
}
public void Pause()
{
Time.timeScale = 0;
pauseGame.Play();
level1Music.Stop();
playerController.enabled = false;
print("We are pressing StartButton and Pausing game.");
}
public void UnPause()
{
Time.timeScale = 1;
pauseGame.Play();
level1Music.Play();
playerController.enabled = true;
print("We are pressing StartButton and UnPausing game.");
}