Problem with High Score displaying

Hello everyone, i am pretty new in Unity C# programming. I followed a tutorial and created a little game. The problem is the score changes but the highscore wont show any change and i dont know why.
I want to know if someone could point me my error or could tell me what is wrong with this code.

Here is my scoreHandler Script :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class scoreHandler : MonoBehaviour {

	public GameObject currentScore;
	public GameObject highScore;

	private TextMesh currentScoreText;
	private TextMesh highScoreText;

	private int current;
	private int high;

	// Use this for initialization
	void Start () {
		//targeting the text mesh components
		currentScoreText = currentScore.GetComponent<TextMesh>();
		highScoreText = highScore.GetComponent<TextMesh>();

		//changing the current score
		currentScoreText.text = PlayerPrefs.GetString("currentScore");

		// check if the current score is greater than the highscore
		current = System.Convert.ToInt32(PlayerPrefs.GetString("currentScore"));
		high = System.Convert.ToInt32(PlayerPrefs.GetString("highScore"));

		if (current > high) {
			PlayerPrefs.SetString("highScore", System.Convert.ToString(current));
		}

		highScoreText.text = PlayerPrefs.GetString("highScore");
	}
}

Hello there,

The void “Start()” actually fires only once, when the object is first enabled. After that, your code usually won’t run again, which is why your highscore isn’t getting updated.

What you probably want to do instead is replace what you have with this:

 void Start () 
{
         //targeting the text mesh components
         currentScoreText = currentScore.GetComponent<TextMesh>();
         highScoreText = highScore.GetComponent<TextMesh>();
 }

void Update()
{
         //changing the current score
         currentScoreText.text = PlayerPrefs.GetString("currentScore");
 
         // check if the current score is greater than the highscore
         current = System.Convert.ToInt32(PlayerPrefs.GetString("currentScore"));
         high = System.Convert.ToInt32(PlayerPrefs.GetString("highScore"));
 
         if (current > high) {
             PlayerPrefs.SetString("highScore", System.Convert.ToString(current));
         }
 
         highScoreText.text = PlayerPrefs.GetString("highScore");
     }

On Start(), you get a reference to the TextMesh objects, and once you have them there’s no need to look for that reference again, so we leave it on Start().

The score and highscore update though, should be updated constantly. Therefore, we are going to put in in the built-in “Update()”, which runs every frame (~60 times a second).

Now this is far from being perfect, but it should at least work.


I hope that helps! Keep learning!

~Cheers,

LegendBacon