Score becomes default (Lecture 72)

Okay… so, when I play Level One, every time I hit a block, it updates the score as normal. But when I complete the level and move on to Level 2, the score becomes my placeholder text and won’t update when I hit a block. It updates in the inspector, but not the actual game graphics itself, so I’m sure it’s a problem with the TextMeshPro text.

Here’s my code for GS (GameStatus) and Block:
Block:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Block : MonoBehaviour {

// Cached reference
Level level;
GS gs;

private void Start()
{
    level = FindObjectOfType<Level>();
    level.CountBreakableBlocks();
}

private void OnCollisionEnter2D(Collision2D collision)
{
    Destroy(gameObject, .1f);
    level = FindObjectOfType<Level>();
    level.BlockDestroyed();
    gs = FindObjectOfType<GS>();
    gs.AddScore();
}

}

and GS:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class GS : MonoBehaviour
{
[Range(0.1f, 10f)] [SerializeField] float gameSpeed = 1f;
[SerializeField] int newScore = 79;
[SerializeField] int score = 0;
[SerializeField] TextMeshProUGUI scoreText;

private void Awake()
{
    int scoreCount = FindObjectsOfType<GS>().Length;
    if (scoreCount > 1)
    {
        gameObject.SetActive(false);
        Destroy(gameObject);
    }
    else
    {
        DontDestroyOnLoad(gameObject);
    }
}

// Start is called before the first frame update
private void Start ()
{
    scoreText.text = score.ToString();
}

// Update is called once per frame
void Update ()
{
    Time.timeScale = gameSpeed;
}

public void AddScore ()
{
    score += newScore;
    scoreText.text = score.ToString();
}

}

I think what is going on is it’s losing the reference to the textmesh when you load your next scene. You might have to parent the canvas to your GS so it persists through your scenes, or find the textmesh reference everytime you load a new scene.

For anyone who ran into a similar problem you do indeed need to make the canvas a child of the Game Status gameObject so that it can persist through to the next scene and the score remains.

However this does cause a problem with the game over screen and the UI we had previously set up. Even if you put your UI elements into a newly prefabbed Game status and canvas game object in the scene, they will be the ones destroyed from the previous scene.

Privacy & Terms