Detecting When a Unity Game is Sent to Background or Closed

Detecting When a Unity Game is Sent to Background or Closed

Detecting When a Unity Game is Sent to Background or Closed

Hello everyone, in this post I will talk to you about 3 Unity functions. These codes will be helpful to you in small situations, such as whether users have sent your game to the background and switched to another app.

void OnApplicationFocus

void OnApplicationFocus( bool hasFocus ) {  
// The operations we want to perform
}

This function normally returns a value of "true" and indicates the player is in the game, but if the player sends the game to the background or, on any mobile device, puts the app on hold and opens another application, it returns "false".

void OnApplicationPause

void OnApplicationPause( bool pauseStatus ) {
// The operations we want to perform
}

This function normally returns a value of "false" and this indicates the player is in the game, but if the player sends the game to the background or switches to another application, it will return "true" and this will mean the player is no longer in the game.

Although the two functions above may seem the same, there are a few small differences between them.

One of these differences is that one returns "true" by default, while the other returns "false". Another is that the "Focus" function will return "false" when, in windowed mode on a computer, you click anywhere outside the application, while onApplicationPause will work when you make another application fullscreen, rather than just clicking on the desktop.

void OnApplicationQuit()

void OnApplicationQuit()  {
// The operations we want to perform
}

This function runs immediately when the player closes the game, and the game shuts down right after. If you want to, for example, save to a save file before the game is closed, you can use this function.

Yes, friends, we have come to the end of this post as well. If you have any questions in your mind or are curious about anything, you can ask here in the comments.