Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Unity3D - How to Detect Pause Event from Game Window

5.00/5 (1 vote)
30 Nov 2016CPOL 9.7K  
How to detect Pause event from Game window

Introduction

Since it took me a day to figure it out and several hours of reading comments and suggestions which didn't quite work, let me help you by saving you time.

Background

I was looking for a way to control Pause event from "Game" window.

To be more specific, I wanted to catch the following event:

Image 1

I read so many answers such as:

C#
void OnApplicationPause( bool pauseStatus )
{
    isPaused = pauseStatus;
}

or:

C#
void OnGUI( )
{
    if( isPaused )

}

which was not what I was looking for.

I continued searching and trying more things like: OnDisable, OnApplicationPause, OnApplicationFocus, OnUpdate, OnLateUpdate, OnFixedUpdate....

I've seen many things like this:

C#
void Update ()
 {
    if(Input.GetKeyDown(KeyCode.P)) //or Input.GetKey(KeyCode.Pause)
    {
        if(Time.timeScale == 1 && playerController.alive == true)
        {
            Time.timeScale = 0;
            showPaused();
        } else if (Time.timeScale == 0 && playerController.alive == true){
            Time.timeScale = 1;
            hidePaused();
        }
    }

At a certain point, I even thought about ways to detect my mouse position and set "hit" event when pressing my mouse, then trying to guess whether I hit the pause button.

Luckily for me, I'm too lazy to do that, so I continued reading and found these two links:

Success!

Using the Code

A breakthrough!
I continued reading more about the play mode and understood that I needed to catch those events.
https://docs.unity3d.com/Manual/GameView.html

C#
using UnityEditor;

        void OnEnable()
        {
        #if UNITY_EDITOR
            EditorApplication.playmodeStateChanged += StateChange;
        #endif
        }

        #if UNITY_EDITOR
        void StateChange()
        {
            if (EditorApplication.isPlayingOrWillChangePlaymode && EditorApplication.isPlaying) 
            {
              Debug.Log("GOT IT");
            }
        }
        #endif
        //-------------------------------------------------------------------------------------

and this is the right event for those issues.

Good luck!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)