Easiest way to pause your Unity game | TimeScale | Pause | Resume | Unity | @Unity3DSchool


PauseManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using UnityEngine;
 
public class PauseManager : MonoBehaviour
{
    bool isPaused = false;
    public GameObject PauseMenu;
    float timeScale;
 
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Escape))
        {
            if(isPaused) Resume();
            else Pause();
        }
    }
 
    void Pause()
    {
        isPaused = true;
        PauseMenu.SetActive(true);
        timeScale = Time.timeScale;
        Time.timeScale = 0.0f;
    }
 
    void Resume()
    {
        isPaused = false;
        PauseMenu.SetActive(false);
        Time.timeScale = timeScale;
    }
}

GameManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System.Collections;
using UnityEngine;
 
public class GameManager : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(DebugCoroutine());
    }
 
    void Update()
    {
        if (Time.timeScale == 0) return;
        Debug.Log("Update is running...");
    }
 
    void FixedUpdate()
    {
        Debug.Log("FixedUpdate is running...");
    }
 
    IEnumerator DebugCoroutine()
    {
        while(true)
        {
            yield return new WaitWhile(() => Time.timeScale == 0);
            yield return new WaitForEndOfFrame();
            Debug.Log("coroutine is running...");
        }
    }
}