How do I make score appear when game is over and record high score?

Hello everyone, I’m new to unity. I’m working on an endless running 2D game. I have successfully added score in the game. Now I want the score to appear when the game is over. I have made the settings so when the game is over new scene is loaded. This is where I want the score made by player to appear. I also want the high score there. Help will be appreciated. Thanks.

EDIT: This is the score code in Player script:

     ...
     public int score = 0;
     public Text scoreText;
 
     void Start() {
         ...
         scoreText.text = score.ToString();
     }
 
         private void OnTriggerEnter2D(Collider2D collision)
         {
             if (collision.tag == "Score")
             {
                 score++;
                 MusicSource.Play();
                 Destroy(collision.gameObject);
                 Instantiate(obstacle, new Vector2(transform.position.x, transform.position.y + 8f), transform.rotation);
                 return;
             }
     
             {
                 Debug.Log("You Died");
                 SceneManager.LoadScene(2);
             }

Hi, you could use a static variable. Static variables will be always the same in all scripts in your scene and if you change scene they will not change the value.

To decleare a static variable write it so:

public static int score;
public static int highScore;

Then create two new UI Texts and name them scoreText and highScoreText. In the script create two Text variables and then assign them in inspector or in script.

public Text scoreText;
public Text highScoreText;

Remember that you need to add using UnityEngine.UI; at the top of your script to access to the UI components.


The high score will only be changed if the score is greater then the current score. To do it simply add an if condition.

if (score > highScore)
{
highScore = score;
}

Then change the text value of your UI Texts:

scoreText.text = score.ToString();
highScoreText.text = highScore.ToString();

@MT369MT Should I create a new script in the new scene? This how I have added score in the Player script:

    ...
    public int score = 0;
    public Text scoreText;

    void Start() {
        ...
        scoreText.text = score.ToString();
    }

        private void OnTriggerEnter2D(Collider2D collision)
        {
            if (collision.tag == "Score")
            {
                score++;
                MusicSource.Play();
                Destroy(collision.gameObject);
                Instantiate(obstacle, new Vector2(transform.position.x, transform.position.y + 8f), transform.rotation);
                return;
            }
    
            {
                Debug.Log("You Died");
                SceneManager.LoadScene(2);
            }