Time freeze (pause game)

With the following script
press ESCAPE key and set time to 0 to freeze the game for pausing the game

when the ESCAPE key is pressed again the game should reset the game time to 1

that works in Unity editor
but with the compiled game when I press ESCAPE it pauses
when pressing the ESCAPE key again it doesn’t reset, the game still pauses or is frozen

Why is that?
It drives me NUTS
because inside the Unity editor it works but NOT with the game outside Unity

function Update () 
{    
	if(Input.GetKeyDown("escape"))	 
	{        
		if (Time.timeScale == 1.0)            
		    Time.timeScale = 0.0;        
		else
		    Time.timeScale = 1.0;	            
	}
}

When you set the Time.timeScale to zero, you have said that “time” should stop. This includes calls to the Update() function which is executed each frame update. But since time has stopped, there are no more frame updates. Using the OnGUI function callback is a place to be called when you still wish callbacks to occur even if time has stopped.

The issue you’re experiencing might be related to the way Unity handles input in different environments, particularly when it comes to the escape key.

using UnityEngine;

public class PauseGame : MonoBehaviour
{
    private bool isPaused = false;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            TogglePause();
        }
    }

    private void TogglePause()
    {
        isPaused = !isPaused;

        if (isPaused)
        {
            Time.timeScale = 0.0f; // Pause the game
        }
        else
        {
            Time.timeScale = 1.0f; // Resume normal time
        }
    }
}

Is this the whole Update code? It should work, but there are some pitfalls relative to setting Time.timeScale to 0 that may cause errors or infinite loops:

1- FixedUpdate isn’t called anymore: if you’re waiting for something to be altered in FixedUpdate, your program will get locked;

2- Time.deltaTime becomes zero, thus if you divide something by this value you will get an exception, and the rest of the function may not be executed.