Loading the previous game level after closing the game

Hi people, I hope this has not been asked before. I did lots of sleepless night searching for this but I did not get the answer I needed. I also checked the unity documentation on PlayerPrefs but I am not sure if I am doing something wrong.

What i am wishing to do is the following: I am making a game which has about 10 levels, and you discover the levels only after succeeding a previous level. so there is no menu to check which level you at. Now I would like to be able to get back to the last level once I have closed the game/app and reopened it. if I close the game at level 5 I want to be able to get it back at level 5 when I open back the application.

Please, any good person out there who can tell me how to achieve this if it is possible.

Thank you

Player Prefs will work for this. As soon as you load a level set(or create and set if one does not exist already) your player pref to your current level number(use an int player pref), make sure you save it or it will be lost when the scene/level ends! Now in your start scene have a check for the existence of the player pref, if it exists get the data(level number) from it and use a “switch”(select) statement in relation to this data to load that level number, if it does not exist load level 1.

Edit : Here are the two code example you asked for :

  1. This should be run when you first load up your game, you will need to put the correct scene names into it :

    #pragma strict

    private var iLevel_To_Load : int = 0;

    function Start() {

     if (PlayerPrefs.HasKey("Load_Level_Number")) {
         iLevel_To_Load = PlayerPrefs.GetInt("Load_Level_Number");
     } else {
         Application.LoadLevel ("Your_Level_1_Name");
     }
     
     if (iLevel_To_Load != 0) {
     
         switch (iLevel_To_Load) {
     
             case 1:
                 Application.LoadLevel ("Your_Level_1_Name");
             break;
             
             case 2:
                 Application.LoadLevel ("Your_Level_2_Name");
             break;
             
             case 3:
                 Application.LoadLevel ("Your_Level_3_Name");
             break;
             
             case 4:
                 Application.LoadLevel ("Your_Level_4_Name");
             break;
             
             case 5:
                 Application.LoadLevel ("Your_Level_5_Name");
             break;
         }
     }
    

    }

  2. Place a copy of this script in every scene, make sure you set the correct scene number for each one :

    #pragma strict

    function Start() {

     //For Level 1, change "1" to whatever the level
     //number is that you have this script on
     PlayerPrefs.SetInt("Load_Level_Number", 1);
     PlayerPrefs.Save();
    

    }