Pause Menu Script TimeScale problems

Hey, so I am making a script for a pause menu, right now I am working on making the system to change between pause and unpause, and whenever I “click” on escape, it opens the pause menu, pauses the game, and in the second right afterwards, it unpauses.

Apparently, whenever I push the button, the delay goes to 1 and starts going down and once it reaches 0, it goes back immediately to 1 and disables the menu. I think it has to do with me keeping my finger on the key for more than a frame or a couple of frames because I don’t get the problem if I push it quickly.

Here is my code:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class PauseMenu : MonoBehaviour
{

    bool opened = false;
    float oldTimeScale = 1.0f;
    float delay;

    void Update()
    {
        if (Time.timeScale != 1)
            delay -= Time.deltaTime * 1000;
        else
            delay -= Time.deltaTime;

        Debug.Log(oldTimeScale + " | " + delay + " | " + opened);

        if (delay < 0)
        {
            if (Input.GetAxis(GetPause()) > 0) //Get Some Input, different pause menu key based on player but doesn't really matter
            {
                delay = 1;
                opened = !opened;
            }
        }

        if (opened)
            DisplayMenu();
        else if (!opened)
            HideMenu();

    }

    void HideMenu()
    {
        GetComponent<Canvas>().enabled = false;
        Time.timeScale = oldTimeScale;

        Debug.Log("Hide");

    }

    void DisplayMenu()
    {
        GetComponent<Canvas>().enabled = true;
        if (Time.timeScale != 0.001f)
            oldTimeScale = Time.timeScale;

        Debug.Log("Display");

        Time.timeScale = 0.001f;
    }


    string GetPause()
    {
        return "PauseP" + PlayerPrefs.GetInt("mainPlayer"); ;
    }

}

Thanks!

Well your script is a mess I’ll do in this way

1)Create a panel with UI

2)Set the gameobject to false

3)Write something like this*
In this way also the audio will be paused

4)Add a button for example an X and as function put OnClick pause the game so if you ve paused it automatically unpaused
It’s all :slight_smile:
*
using UnityEngine;
using System.Collections;
public class PauseMenuScript : MonoBehaviour
{
public bool CanPause;
public bool CanSound;
public GameObject PausePanel;
public string levelToLoad;
void Start() {
CanPause = true;
CanSound = true;
PausePanel.SetActive (false);
AudioListener.pause = false;
}

	public void pauseGame()
	{
		if (CanPause)
		{
			Time.timeScale = 0;
			AudioListener.pause = true;
			CanPause = false;
			PausePanel.SetActive (true);
		}
		else
		{
			Time.timeScale= 1;
			AudioListener.pause = false;
			CanPause = true;
			PausePanel.SetActive (false);
		}
	}
}