How would I add a persistent high score?

Viewed 44

I was following a tutorial to make a game in unity C# and I need to know how I would add a High Score which persists among game restarts. I'm new to making games so any help is apreciated, and if I need to elaborate on anything please mention that.

public class UIManager : MonoBehaviour
{
    void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else
        {
            DestroyImmediate(this);
        }
    }

    private static UIManager instance;
    public static UIManager Instance
    {
        get
        {
            if (instance == null)
                instance = new UIManager();
            
            return instance;
        }
    }

    protected UIManager()
    {
    }

    private float score = 0;

    public void ResetScore()
    {
        score = 0;
        UpdateScoreText();
    }
    
    public void SetScore(float value)
    {
        score = value;
        UpdateScoreText();
    }

    public void IncreaseScore(float value)
    {
        score += value;
        UpdateScoreText();
    }
    
    private void UpdateScoreText()
    {
        ScoreText.text = score.ToString();
    }

    public void SetStatus(string text)
    {
        StatusText.text = text;
    }

    public Text ScoreText, StatusText;
}
1 Answers

PlayerPrefs helps you to store game data.

Usage:

void SaveHighScore(float value)
{
    PlayerPrefs.SetFloat("HighScore", value);
}

void LoadHighScroe()
{
    float hs = PlayerPrefs.GetFloat("HighScore", 0.0f); // 0.0f here is default value when key/value not exest in PlayerPrefs
    ScoreText.text = hs.ToString();
}

Related