- Home /
How do I save and retrieve the high score?
enter code here
I have been using this code and want to display the high score with the current score when the game ends. Can someone please help me out?
[CODE]
using UnityEngine; using UnityEngine.UI; using System.Collections;
public class ScoreManager : MonoBehaviour
{
public static int score;
Text text;
void Awake ()
{
text = GetComponent <Text> ();
score = 0;
}
void Update ()
{
text.text = "Score: " + score;
}
}
[/CODE] Thank you!
Post code using code block so it is readable for us to answer. Secondly mention the issues you are having.
Answer by UsmanAbbasi · May 02, 2016 at 09:40 AM
ScoreManager : MonoBehaviour {
public static int currentScore;
public static int highScore;
Text currentScoreText;
Text highScoreText;
void Awake ()
{
//this is how you get "Text" component.
//"CurrentScoreValue" is the name of gameobject which has "Text" component attached to show value of current score.
currentScoreText = GameObject.Find ("CurrentScoreValue").GetComponent <Text>();
//"HighScoreValue" is the name of gameobject which has "Text" component attached to show value of high score.
highScoreText = GameObject.Find ("HighScoreValue").GetComponent <Text>();
score = 0;
}
void GameOver()
{
currentScoreText.text = currentScore.toString();
if( PlayerPrefs.GetFloat("High Score", 0) > currentScore)
{
highScoreText.text = highScore.toString();
//You need this to save high score across game sessions
PlayerPrefs.SetFloat("High Score", highScore);
}
}
}
You need to call "GameOver()" when game is over. Also you need to set value of "currentScore" variable and "highScore" variable properly.
P.S: Here is the link to PlayerPrefs in case you are not familiar with it. http://docs.unity3d.com/ScriptReference/PlayerPrefs.html
Thank you! And how would I call GameOver in another script exactly?
Answer by Outliver · May 02, 2016 at 10:34 AM
I, personally, like to have structs for my highscores, say a TopListEntry with the player name and an integer value for the actual scrore. (if you don't need to keep references to player profiles or whatever)
You COULD save that into your PlayerPrefs but that's not what they're for. I would rather serialize the data and then save it to Application.persistentDataPath. That makes it more secure against highscore-hackers as well ;)
PlayerPrefs are for... well... player prefs - gameplay options and stuff you set from the menu.