Pause the Game

Hi everbody,

I’m looking on a solution for 6 hours now. I’m going to pause my game.
First step I’ve tried: Set Time.timeScale = 0, that works, but only for Rigidbodys. I also have other GameObjects like AudioSources, Cameras and so on. How can I make, that every Component stops working?

Thanks a lot, Michael

Of course, I’ve tried to get every Object

public bool paused;

    // Use this for initialization
    void Start () {
        paused = false;   
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.P))
        {
            print("p pressed");
            paused = !paused;

        }
        if (paused)
        {
            Time.timeScale = 0;
            AudioSource[] audioFiles = GameObject.FindObjectsOfType<AudioSource>();
            for (int i = 0; i < audioFiles.Length; i++)
            {
                audioFiles[i].enabled = false;
            }
        }
        else if (!paused)
        {
            Time.timeScale = 1;
            AudioSource[] audioFiles = GameObject.FindObjectsOfType<AudioSource>();
            for (int i = 0; i < audioFiles.Length; i++)
            {
                audioFiles[i].enabled = true;
            }
        }
    }

But I don’t think that it is the right way?

One thing you can do is create something like a Game Manager component with a static bool IsPaused field. Set it when you pause/unpause, and check it at the start of every update. Return from the update if the game is paused.

1 Like

Did you mean something like this?

 static bool isPaused;

    // Use this for initialization
   
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.P))
        {
            isPaused = true;        
        }
        else
        {
            isPaused = false;
        }
    }

sure, and then in every other script you have:

void Update()
{
    if(GameManager.IsPaused) return;

    // all your regular update stuff goes here.
}

also, I like the way you were setting pause earlier:

if(Inpug.GetKeyDown(KeyCode.P))
{
    paused = !paused;
}
1 Like

Thanks for your help, it works, perfect :slight_smile: