Changing Level - PlayerPrefs - Help!

Hello everyone.
Im currently learning how to use PlayerPrefs. i understood pretty much how it works, but when i save the score for example, (score : 5), in the level 2 it shows (score : 5) but as soon i get one more point, it overwrites on the 5, the number 6. and for the whole level 2, i have written the 5, and over it the new numbers are appearing.

Same with lives. Any idea how to make number 5 move to 6? Instead of just staying on the screen?
im guessing it has to do with:

Thanks in advance :slight_smile:

Level 1:

Level 2

Level ++ etc…

Since i set in level 2 in Start Function

Should the score been replaced?

If you don’t want the player to retain the score from level one, then you should set a different key to the PlayerPrefs method in level two. Like so:

Level 1:

PlayerPrefs.SetInt("Level1Score",score);

Level 2

PlayerPrefs.SetInt("Level2Score",score);

Or, if you want the player to retain his score after level completion, it should be like so:

Level 1:

static var score : int = 0;

PlayerPrefs.SetInt("Score",score);

Level 2:

var HighScore : int = PlayerPrefs.GetInt("Score");
static var Score : int = Level1Script.score;  //Where Level1Script should be replaced with the actual script name.


function Update(){
if(Score > HighScore){
PlayerPrefs.SetInt("Score",Score);
}
}

Also, you should try to stay away from using static variables when you don’t have to. Make a reference to the script in question instead.

Furthermore, when dealing with multiple levels, it is usually always best to implement a GameManager. This would probably simplify your problem by quite a bit. Just google “unity gamemanager” and have a read.

Isn’t it easier just to overwrite the score when a new level starts?

I see what you mean. But this is not what i meant. Overwrite as GUI on GUI
I took pic of it.
Level 1:

Imgur

Level 2:

Imgur

maybe this way its more understood. I think its a GUI problem. which one stays over the other. but i cant figure it out.

Im not sure if pictures are visible. So i uploaded a link as well

I think the problem is that the GUI don’t know the PlayerPrefs have changed.

Try to put the function add score in the Update before you set Prefs.

function Update () {

     if ( lives <= 0) {

          AddScore(); <<-- calling the add score
          PlayerPrefs.SetInt("SCORE",score); <<-- write new score after addition
          Application.LoadLevel("SceneLose");
          lives =3;
          score2 = 0;

}

I would always put such “actual data” in the update. It is like my PlayerPosition. It saves also in update permanently.

When you load level 2, make sure that the Level 1 script has been disabled. That is why.

This is why you should have a GameMaster object that holds all of the OnGUI functions.

Thanks. It works.
I added the AddScore() in the updates and it seems like the script from level 1 was running with the script of level 2.

Works like a charm :slight_smile:

Thanks again