- Home /
Saving Highscore
I have code that calculates score based on distance. How would I go about getting this code to remember the high score after the game is quit? Thanks in advance.
#pragma strict
var player : Transform;
function Update ()
{
var dist : int = Vector3.Distance(player.position, transform.position);
print ("Distance : " + dist);
var score : int = dist / 5.5;
guiText.text = "Score : " + score;
}
Answer by POLYGAMe · Feb 22, 2014 at 02:07 AM
Use player prefs:
PlayerPrefs.SetInt("score", score); // The first is the string name that refers to the saved score, the second is your score variable (int)
PlayerPrefs.Save()
Then to load it when you start next time (maybe in function Start()):
score = PlayerPrefs.GetInt("score");
Please note that code is off the top of my head. The syntax/letter capitalization could be a bit off.
This is a good first implementation of saving. Though depending on the size of the game and target platform you will want to look into serialization for saving your stats and other objects.
I figure in this case player prefs is perfectly adequate :)
I must have something wrong. This is what I have.
#pragma strict
var player : Transform;
var highscore : int;
var highscoreGUI : boolean = false;
var scoreGUI : boolean = false;
function Update ()
{
if(scoreGUI)
{
var dist : int = Vector3.Distance(player.position, transform.position);
print ("Distance : " + dist);
var score : int = dist / 5.5;
guiText.text = "Score : " + score;
if(highscore > score)
{
highscore = score;
PlayerPrefs.SetInt("highscore", score);
PlayerPrefs.Save();
}
}
if(highscore)
{
guiText.text = "highscore : " + score;
}
}
Well your logic is wrong for a start. It should be if score > high score, then high score = score, or else your high score will always be the same as score or lower. Other than that, it will work. You're not loading the high score though, just saving.
Also, probably best not to use PlayerPrefs.Save() in update like that. Just use it at the end of the game/turn, as it can cause hiccups, due to writing to disk.
Answer by jpsmarinho812 · Feb 22, 2014 at 03:40 AM
POLYGAme is correct. My I think that without PlayerPrefs.Save() works correctly. I used in my game and works.
If you need to test if a variable already exists, use PlayerPrefs.HasKey("score");
Use this before PlayerPrefs.GetInt("score");
public int GetScore () {
if(!PlayerPrefs.Has$$anonymous$$ey("Score")){
PlayerPrefs.SetInt("Score",0);
}
return PlayerPrefs.GetInt("Score");
}
public void SetScore(int value){
PlayerPrefs.SetInt("Score",value);
}
In this case, if you call GetScore() before of SetScore(), the funcion will create the variable Score with value equals zero.
You can learn more about persistance date in here: http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/persistence-data-saving-loading