- Home /
I need some help with my high score.,I need help with my highsore.
Hello, i am new to coding and just followed Brackey's "how to make a video game" series. Now i am trying to add a high score in my game. I have got something working here:
using UnityEngine; using UnityEngine.UI;
public class Dice : MonoBehaviour {
public Text score;
public Text highscore;
public Transform player;
void Start()
{
highscore.text = PlayerPrefs.GetString("Highscore");
}
void Update()
{
PlayerPrefs.SetString("Highscore", score.text);
}
}
This is probably not the best way to do this at all but now in my game it saves the high score in the correct text but it does it every time the player dies ans does not save the highest score, just the previous one. Could someone explain how I can make this work as I can't use "<" or ">" in an if statement because my score and high score are strings. Please help!
Answer by UnityCoach · Jan 29, 2018 at 11:05 PM
First, I guess your score isn't a string, but rather an int or other number type.
You can use a property accessor, like this :
int _highScore = -1; // initialise at -1 so that you know when you haven't fetched it yet
int highScore
{
get
{
if (_highScore == -1)
_highScore = PlayerPrefs.GetInt ("highscore", 0); // default value 0
return _highScore;
}
set
{
PlayerPrefs.SetInt ("highscore", value); // update value
hsText = string.Format ("High Score : {0}", value); // update text
}
}
string hsText = "High Score";
By the way, if you're interested, I've covered this topic fully in my introductory course.
Your answer
Follow this Question
Related Questions
How do I save and retrieve the high score? 2 Answers
Multiple Cars not working 1 Answer
How do you check if a game object is set active using an if statement? 2 Answers
I'm trying to allow my character to only jump when grounded 1 Answer
error CS1525: unexpected symbol. How do I fix this and why am I getting this error? 1 Answer