Game over screen not displaying proper score.

In my game it’s game over if an enemy touches the player. When this happens they are taken to the game over screen which also shows their score. Currently whenever the player gets a game over the score on the game over screen is shown as 0. I know the score script is working properly because it shows the correct score in the inspector when I click on the score object. So it’s probably either the game manager or game over screen script.

Score script

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

public class Playerscore : MonoBehaviour
{
    public static float scoreValue = 0f;
    public float ChangePerSecond;
    Text score;
    // Start is called before the first frame update
    void Start()
    {
        score = GetComponent<Text>();
    }

    // Update is called once per frame
    void Update()
    {
        scoreValue += ChangePerSecond * Time.deltaTime;
        score.text =  ""+ (int)scoreValue;
    }
}

Game over screen script

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

public class GameOverScreen : MonoBehaviour
{
    public Text pointsText;
    public void Setup(int score)
    {
        gameObject.SetActive(true);
        pointsText.text = score.ToString() + " Points";

    }
}

Game manager script

using UnityEngine;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
   
    public  int scoreValue;
    public GameOverScreen GameOverScreen;
    bool gameHasEnded = false;
  

    public void EndGame()
    {
        if (gameHasEnded == false)
        {
            gameHasEnded = true;
            //Debug.Log("game over");
            GameOverScreen.Setup(scoreValue);
        }
       
    }
}

Your Game Manager is using its own local scoreValue instead of the Playerscore.scoreValue

Right now your Playerscore script has a float variable that is incremented in Update. While this is fine if your game requires that, nothing stops it from incrementing if the game ends right now. However, this is not the source of your error.

Next, your GameManager scoreValue is an int. This int has a default value of 0. When you call GameOverScreen.Setup you are passing 0 over. You could figure this out using Debug.Log calls easily.

In other words, your code is doing what you are telling it to.

How would Debug.Log calls have helped? I thought they were only useful if you are not sure that all lines of code are running. Also how do I stop the score from incrementing while the player is dead?

You can use Debug.Log to print out values of variables to see what that value is. That helps a ton.

If you are using Update for incrementing score constantly, then you need a bool value that you can set to true to stop the count. So, if Update checks “isDead” and it returns true, then it needs to stop incrementing the value.

1 Like