- Home /
Help with pausing script.
When I press 'P' the game will pause, and there is supposed to be GUI coming up. The game pauses but the only thing is that the GUI won't show up and there are no errors. Here's my script.
using UnityEngine;
using System.Collections;
public class Pause : MonoBehaviour {
public float x;
public float y;
public float sizex;
public float sizey;
// Use this for initialization
void Start () {
Time.timeScale = 1;
}
// Update is called once per frame
void Update () {
}
void OnGUI()
{
if(Input.GetKeyUp(KeyCode.P))
{
Time.timeScale = 0;
GUI.Box(new Rect(x, y, sizex, sizey), "Paused");
}
}
}
Answer by clunk47 · Nov 24, 2013 at 06:43 PM
Don't use GetKey inside your GUI code. Only place GUI methods in GUI. You need to place your GetKey function inside of Update so it will be checked every frame. If you're wanting to toggle the pause w/ the P key, use a bool that is toggled by GetKey.
using UnityEngine;
using System.Collections;
public class Pause : MonoBehaviour
{
public float x;
public float y;
public float sizex;
public float sizey;
bool pause = false;
void Update ()
{
if(pause)
Time.timeScale = 0;
else
Time.timeScale = 1;
if(Input.GetKeyDown (KeyCode.P))
pause = !pause;
}
void OnGUI()
{
if(pause)
GUI.Box(new Rect(x, y, sizex, sizey), "Paused");
}
}
Answer by kensct · Nov 24, 2013 at 06:47 PM
The GUI.Box(new Rect(x, y, sizex, sizey), "Paused"); need to be outside of the if statement.
Here:
bool paused;
void Update () {
if(Input.GetKeyUp(KeyCode.P))
{
Time.timeScale = 0;
paused = true;
}
void OnGUI()
{
if(paused)
{
GUI.Box(new Rect(x, y, sizex, sizey), "Paused");
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613122638im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Draw GUI Text if clicked out of webplayer 1 Answer
Setting Scroll View Width GUILayout 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Two Unity GUI questions 2 Answers
Adding a floating health bar 2 Answers