- Home /
How do I toggle my pause menu with escape?
I am adding a pause menu in my game and its going pretty well. But I just can't get my head around this problem right now.
Im using a canvas that is deactivated at the start and when you press esc it should pop up. That worked, but when I wanted it to go away when I press esc again it started to flicker if I held the esc key.
Here's my code:
using UnityEngine;
using System.Collections;
public class Pause : MonoBehaviour {
public GameObject Canvas;
public GameObject Camera;
bool Paused = false;
void Start(){
Canvas.gameObject.SetActive (false);
}
void Update () {
if (Input.GetKey ("escape")) {
if(Paused == true){
Time.timeScale = 1.0f;
Canvas.gameObject.SetActive (false);
Screen.showCursor = false;
Screen.lockCursor = true;
Camera.audio.Play ();
Paused = false;
} else {
Time.timeScale = 0.0f;
Canvas.gameObject.SetActive (true);
Screen.showCursor = true;
Screen.lockCursor = false;
Camera.audio.Pause ();
Paused = true;
}
}
}
public void Resume(){
Time.timeScale = 1.0f;
Canvas.gameObject.SetActive (false);
Screen.showCursor = false;
Screen.lockCursor = true;
Camera.audio.Play ();
}
}
The resume function at the bottom is for the resume button. So you could resume with the button or with esc.
Help would be appreciated.
Answer by Baste · Oct 18, 2014 at 10:08 AM
The problem here is that you're using Input.GetKey ("escape"). Input.GetKey works like an autofire - the method returns true on every frame that you're touching the button. That's probably what's causing the flickering.
Replace it with Input.GetKeyDown, which only fires once for every keypress. That should fix it.
Answer by AaronC · Nov 20, 2015 at 11:39 PM
I am just going to add the craziest tip.. Escape would not work for me no matter what I tried.
Eventually I found a discussion that said that Photoshop being open, could stop the escape key working altogether.
Sure enough, I closed Photoshop and all versions of getting input from the escape key worked. posting this now in case it helps someone else with this issue.
Your answer
Follow this Question
Related Questions
Pause Menu won't open... 1 Answer
Escape key not working 1 Answer
Pause Game 1 Answer