My ScoreHander looses connection to ScoreText when changing scenes

When changing form the GameScene to the GameOver scene, my score text is no longer connected to the ScoreHandeler.cs script, and does not show the score anymore, but only the text I entered directly in TMPro in my case 12345678.

I put this line in ScoreHandler.cs to check if the score is correctly carried over:

Debug.Log("Score: " + gameStatus.GetScore().ToString());

The score is correctly carried over to the GameOver Scene, so the problem seems to be the link between ScoreHandler and the TMpro, if I run the GameOver scene directly it works, its only if its called from the Game scene there is a problem, before running the Game the text and the script is correctly set up in the inspector for both scenes, but after entering the GameOver Scene from the Game Scene the inspector indicates: “Score Text Missing (Text Mesh…”

I checked that the singletons are working, and there is only one of each, as there should be. (DontDestroyOnLoad).

The ScoreHandeler.cs is set up as a singeleton, and looks like this:

using TMPro;
using UnityEngine;


public class ScoreHandler : MonoBehaviour
{

    [SerializeField] TextMeshProUGUI scoreText;
    GameStatus gameStatus;

    private void Awake()
    {
        SetUpSingeleton();
    }
    private void SetUpSingeleton()
    {
        if (FindObjectsOfType(GetType()).Length > 1)
        {
            gameObject.SetActive(false);
            Destroy(gameObject);
            
        }
        else
        {
            DontDestroyOnLoad(gameObject);
        }
    }
    
    // Start is called before the first frame update
    void Start()
    {
        gameStatus = FindObjectOfType<GameStatus>();
        scoreText.text = "Score: " + gameStatus.GetScore().ToString();
    }

    // Update is called once per frame
    void Update()
    {
        scoreText.text = "Score: " + gameStatus.GetScore().ToString();
       Debug.Log("Score: " + gameStatus.GetScore().ToString());
    }

}

Hi Karsten,

Is the Score Text game object a child of the game object to which you assigned your “singleton” script?

Hi Nina.

The Score Text game object is child of the Canvas.

The Score Handler game object which has the singleton script assigned to it is alone at the top level of the Hierarchy.

When a new scene gets loaded, all game objects but the ones on which you called DontDestroyOnLoad get destroyed. Since your Score Text game object is not parented to the persistent game object, it gets destroyed.

That solved it, thanks Nina.

I was expecting the newly instantiated ScoreText to know it would refer to the persistent ScoreHandler, but as it turns out its not the case.

Good to continue the learning journey.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms