0

I'am beginner in coding. I'am trying to make a game, so when the player hits an object then adds +1 point to my score variable. I think I've made it succesful, but I want to save this score to highScore. My problem is: When I restart the game than high score is again equal to score. So the high score is not saved. Can somebody help me?

Here is my code:

public Text highScoreText;       
public TextMeshProUGUI goalScore;

public int highScore;                                                     
public int score;

void start()

    highScore = PlayerPrefs.GetInt("High Score", 0);                 
    highScoreText.text = "High Score: " + highScore;

    UpdateScore();

public void UpdateScore()

    score ++;
    goalScore.text = "Goals: " + score;
    highScoreText.text = "High Score: " + highScore;                    
    if (score > highScore)                                              
    {
        highScore = score;                                                 
        highScoreText.text = "High Score: " + score;                 
    }
Cleptus
  • 3,446
  • 4
  • 28
  • 34
  • Does this answer your question? [saving state between program restarts](https://stackoverflow.com/questions/7522228/saving-state-between-program-restarts) – Sinatr Apr 17 '20 at 10:22
  • Check [those](https://www.google.com/search?q=c%23+save+data+between+restarts+site%3Astackoverflow.com) until you find a method which you like the most. – Sinatr Apr 17 '20 at 10:23

1 Answers1

0

You can create a text file for this purpose. It's pretty simple. Here an example, you may not use static functions for your code.

using System.IO;
using System.Text;

static string resultFileName = "result.txt"; // Can be path for your file also.
public static void ReadResult() // Can be private, It's up to you.
{
    if (!File.Exists(resultFileName))
    { 
        highScore = 0; // Assumption
    }
    else
    {
        string line;
        StreamReader fileStreamReader =
            new StreamReader(resultFileName);
        if ((line = fileStreamReader.ReadLine()) != null)
        {
            highScore = int.Parse(line);
        }
        fileStreamReader.Close();
    }
}

public static void SaveResult() // Can be private, It's up to you.
{
    if (score > highScore)
    {
        highScore = score;
        string scoreStr = string.Format("{0}\n", score);
        FileStream scoreFile = File.OpenWrite(resultFileName);
        scoreFile.Write(Encoding.ASCII.GetBytes(scoreStr), 0, scoreStr.Length);
        scoreFile.Close();
    }
}
Dor
  • 1
  • 1