3

Hi there I made a game for Android using Unity. My problem is that when I background the app by pressing the home button and then relaunch the game from the taskbar menu or by clicking the icon, my game is relaunching from Scene 0 instead of restarting from its last state. This is not always happening. Sometimes it does sometime it dosen't. Is this a problem with my device (Samsumg Galaxy S7) or is something I can correct through code?

Programmer
  • 121,791
  • 22
  • 236
  • 328
Raducu Mihai
  • 313
  • 4
  • 14

1 Answers1

3

This is handled differently on each Os. For Android, there many things that determines if the state of the App should be in the memory. This includes memory size, Android version, how many apps are running in the background.

Because of this, it is your responsibility to implement a save on exit mechanism. This can be done with the OnApplicationPause or OnApplicationFocus function.

The code below is an example of what you should do. You need to modify it and add more information such as player information, score, play, player position. It would make sense to save them as a json file.

string leveName = "";
void Start()
{
    //Get current scene name
    leveName = SceneManager.GetActiveScene().name;
}

void OnApplicationPause(bool paused)
{
    //Save scene Name if paused, otherwise load last scene
    if (paused)
    {
        PlayerPrefs.SetString("myLastScene", leveName);
        PlayerPrefs.Save();
    }
    else
    {
        //Load last scene
        string lastScene = PlayerPrefs.GetString("myLastScene");
        SceneManager.LoadScene(lastScene);
    }
}
Programmer
  • 121,791
  • 22
  • 236
  • 328
  • I am using the OnApplicationPause method but I didn't implemented a save on exit mechanism. I will do that as soon as I can access my PC and I'll let you know if it works or not. Thanks for your help! – Raducu Mihai Oct 22 '16 at 12:38
  • Ok. You should also see [here](http://stackoverflow.com/a/40097623/3785314) for how to save multiple game data with josn. – Programmer Oct 22 '16 at 14:49
  • 1
    Sorry it took so long but I didn't have time to try this. Now I've done it and it works. Thanks! – Raducu Mihai Oct 24 '16 at 14:47