How to pause a countdown timer?

In-game, I have a countdown timer. I want the countdown timer to pause when the player pause but it resets when he resumes the game. How to make the countdown timer pause? Here are the scripts.

Timer Script

[SerializeField] private Text uiText;
[SerializeField] private float mainTimer;

private float timer;
private bool canCount = true;
private bool doOnce = false;

void Start()
{
    timer = mainTimer;
}

void Update()
{
    if (timer >= 0.0f && canCount)
    {
        timer -= Time.deltaTime;
        uiText.text = timer.ToString("F");
    }

    else if (timer <= 0.0f && !doOnce)
    {
        canCount = false;
        doOnce = true;
        uiText.text = "0.00";
        timer = 0.0f;
        GameOver();
    }
}



void GameOver()
{
    SceneManager.LoadScene("Game Over");
}

Pause Script

    public static bool GameisPaused = false;
    public GameObject pauseMenuUI;
// Update is called once per frame
void Update () {
    if (Input.GetKeyDown(KeyCode.Escape))
    {
        if (GameisPaused)
        {
            Resume();
        }else
        {
            Pause();

        }
    }
}
public void Resume ()
{
    SceneManager.LoadScene("Game");

    Time.timeScale = 1f;
    
}
void Pause ()
{
   
    Time.timeScale = 0f;
    
    SceneManager.LoadScene("Game Option");
}

You reload the scene on every resume. By reloading the scene you reload all its objects, scripts and variables.


To not reset the scene, use ‘LoadSceneMode.Additive’ when you load “Option” scene, it will add the scene over the game as a layout and your game scene won’t be reset, and unload the “Option” scene on resume instead of reloading the “Game” scene:

void Pause ()
{
    Time.timeScale = 0f;
     SceneManager.LoadScene("Game Option", LoadSceneMode.Additive);
 }
 
public void Resume ()
{
     SceneManager.UnloadSceneAsync("Game Option");
     Time.timeScale = 1f;
}