Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save game when exiting app

Tags:

c#

unity3d

I am making a game with unity C#. I have code a save local and save cloud for the game. I make a button exit when pressed the game is saved and then exit.

But i have a problem in here saved game. When someone or player press the home button which on device mobile the game will exit and run in background.

If the player restart the device the game that run in background will not saved to local or cloud. This is the problem.

So in unity when home button pressed at device mobile what will unity do ? It is pause the application / game or whatever ? What can we do in unity if the player press the home button ?

If it pause the application / game could we detect it first when the player press the home button we could do saving the game ? ( i mean run a code after the button home is pressed )

Or any idea from your experience what will do if player press home button ? This is for the player to not lose the game data.

Please give the detail for me to find the solution.

Any help would be amazing for continue the game :)

Thanks

Dennis

like image 273
Dennis Liu Avatar asked Jan 06 '17 10:01

Dennis Liu


1 Answers

So in unity when home button pressed at device mobile what will unity do ?

Unity does not control this. The OS does. You did not mention which OS (Android or iOS) but you can research what happens when the home button is pressed for each one.

What I can tell you is that the app is suspended for a while on Android. Sometimes, the assets are unloaded by Android. This depends on many factors such as how long the app has been suspended, how many apps are open and the memory available on the device.

You can't depend on the OS to handle this. You must handle it yourself.

If it pause the application / game could we detect it first when the player press the home button we could do saving the game ?

Yes and No.

You should not detect when the Home Button is pressed in order to do something. You should however detect when the Game is paused and resumed.

This is what the OnApplicationPause function is used for. Another similar function is OnApplicationFocus but OnApplicationPause is more approprite for this.

When OnApplicationPause( bool pauseStatus ) is called when the Home Button is pressed, the pauseStatus parameter is true. When the app is re-opened, pauseStatus parameter is false.

This is for the player to not lose the game data

You save and load the data depending on pauseStatus value.

Here is what to do:

void OnApplicationPause(bool pauseStatus)
{
    if (pauseStatus)
    {
        Debug.Log("Paused");
        //Save Player Settings
        //https://stackoverflow.com/q/40078490/3785314
    }
    else
    {
        Debug.Log("resumed");
        //Load Player Settings
        //https://stackoverflow.com/q/40078490/3785314
    }
}
like image 106
Programmer Avatar answered Sep 28 '22 07:09

Programmer