0
votes

I have a script that gives you 1 point every 1 second.

I was wondering how to save the score as a high score. I know about PlayerPref, but I can't get my head around it. I've also tried out several other explanations.

using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class score : MonoBehaviour
{
    private Text scoreText;
    private float PIPS;
    public GameObject gameOverScore;
    public GameObject Player;
    public static float scoreAmount;

    public void Start()
    {
        scoreText = GetComponent<Text>();
        scoreAmount = 0.0f;
        PIPS = 1.0f;
    }

    public void Update()
    {
        if (Player.activeInHierarchy == true)
        {
            scoreText.text = scoreAmount.ToString("F0");
            scoreAmount += PIPS * Time.deltaTime;
        }
        else
        {
            scoreText.enabled = false;
            gameOverScore.GetComponent<TextMeshProUGUI>().text = scoreAmount.ToString("F0");
        }
    }
}
2

2 Answers

0
votes

Here is an Instance from one of my Scripts -->

int HighScore = PlayerPerfs.GetInt("HighScore", 0) //If playing First Time Score = 0
void Save()
    {
        if(ScoreUpdate.CurrentScore > HighScore) //Check if CurrentScore is more than HighScore
        {
            PlayerPrefs.SetInt("HighScore", ScoreUpdate.CurrentScore);//Save New High Score
        }
    }

You Now Just Need To Call This Function Save() whenever the Game get complete or player dies (if dies at any point)

Edit : Replace Your Variables on place of ScoreUpdate

0
votes

While this is not the ideal way, you can use playerprefs on Awake and OnDisable().

using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class score : MonoBehaviour
{
private Text scoreText;
private float PIPS;
public GameObject gameOverScore;
public GameObject Player;
public static float scoreAmount;
public float HighScore;

public void Start()
{
    scoreText = GetComponent<Text>();
    scoreAmount = 0.0f;
    PIPS = 1.0f;
}

private void OnDisable()
{
    // this will save the highscore in playerprefs when the game ends[application quit].

    PlayerPrefs.SetFloat("HighScore", HighScore);
}

private void Awake()
{
    // this will load the highscore from playerprefs
    HighScore = PlayerPrefs.GetFloat("HighScore");
}

public void Update()
{
    if (Player.activeInHierarchy == true)
    {
        scoreText.text = scoreAmount.ToString("F0");
        scoreAmount += PIPS * Time.deltaTime;
        if (scoreAmount > HighScore)
        {
            HighScore = scoreAmount;
        }
    }
    else
    {
        scoreText.enabled = false;
        gameOverScore.GetComponent<TextMeshProUGUI>().text = scoreAmount.ToString("F0");
    }
}
}

let me know if this helps.