-2

I am making a maze game in unity 3d where the least time taken to complete the level is the highscore. Is there a way to save the highscore using Playerprefs? Scripting is done in C#.

  • 1
    So to reduce your question to the essential: [Saving/loading data in Unity](https://stackoverflow.com/questions/40078490/saving-loading-data-in-unity) or [How to use `PlayerPrefs` - Official tutorial video](https://www.youtube.com/watch?v=J6FfcJpbPXE&t=435s) – derHugo Jun 02 '20 at 07:18

3 Answers3

1

You can make it easier using Get/Set Assessors.

public class GameManager: MonoBehavior {
    ...
    public float HighScore {
        get {
            return PlayerPrefs.GetFloat("HIGHSCORE", 0);
        }
        set {
            if(value > HighScore) {
                PlayerPrefs.SetFloat("HIGHSCORE", value);
            }
        }
    }
    ...
    public void GameOver() {
        HighScore = currentScore;
    }
}
gmspacex
  • 642
  • 5
  • 12
0

You can first put this check in your homescript in awake function:

   if(!PlayerPrefs.HasKey("HighestScore"))
        {
            PlayerPrefs.SetString("HighestScore", "keep some big number");
        }

Or alternatively can use (Preferably)

if(!PlayerPrefs.HasKey("HighestScore"))
            {
                PlayerPrefs.SetFloat("HighestScore", 100000f);
            }

Then when the particular level ends and you need to save the score Compare the existing PlayerPref with the current Player score.

For example for float

if(PlayerPrefs.GetFloat("HighestScore")>=current_score)
{
PlayerPrefs.SetFloat("HighestScore",current_score);
}

Hope this helps !

Aditya Patil
  • 123
  • 1
  • 1
  • 9
0

Thanks I got the answer! Just needed to check if the first round had already taken place or not.

// Start is called before the first frame update
void Start()
{



    HighScore = score;



    WinScore.text = PlayerPrefs.GetFloat("HighScore").ToString();



}

// Update is called once per frame
void Update()
{
    if(PlayerPrefs.GetFloat("HighScore") == 0f)
    {

        PlayerPrefs.SetFloat("HighScore", (float)HighScore);
        WinScore.text = HighScore.ToString();


    }

    if (HighScore < PlayerPrefs.GetFloat("HighScore")){ 

        PlayerPrefs.SetFloat("HighScoreEasy", (float)HighScore);
        WinScore.text = HighScore.ToString();


    }

}