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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With