ExConfessor
ExConfessor

Reputation: 55

Singleton – extra script not destroyed?

I want to have a singleton which will store, update and show player score through all levels (scenes), but something works wrong.

This my singletone script GameStatus.cs:

using UnityEngine;
using TMPro;

public class GameStatus : MonoBehaviour
{
    public static GameStatus instance;

    [SerializeField] int pointsPerBlock = 50;
    [SerializeField] TextMeshProUGUI scoreText;

    [SerializeField] public static int currentScore = 0;

    private void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);
        }
        else
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
    }
    public void AddToScore()
    {
        currentScore += pointsPerBlock;
        scoreText.text = currentScore.ToString();
    }
}

I also have another script for objects player need to destroy, called Block.cs. Here it is:

using UnityEngine;

public class Block : MonoBehaviour
{
    Level level;
    GameStatus gameStatus;

    private void Start()
    {
        level = FindObjectOfType<Level>();
        gameStatus = FindObjectOfType<GameStatus>();

        level.CountBreakableBlocks();
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        DestroyBlock();
    }

    private void DestroyBlock()
    {
        level.BlockDestroyed();
        gameStatus.AddToScore();
        Destroy(gameObject);
    }
}

And on level 1 everything works fine, but when the game goes to the next level this happens:

  1. Player score stops updating.

  2. If I use Debug.Log(currentScore); in GameStatus.cs I can see that this variable doesn't change when player breaks blocks, but if use Debug.Log(gameStatus.currentScore); in Block.cs then I can see that this variable is getting updated.

  3. Debug.Log(FindObjectsOfType().Length); shows that there is one GameStatus object in the first level and two objects in the next levels, although I can't see the second one GameStatus in hierarchy.

So my question is - what's wrong and how to fix it?

Upvotes: 0

Views: 105

Answers (1)

Nikolay Gonza
Nikolay Gonza

Reputation: 613

If you use singleton, there is no point to make

currentScore 

static variable, just make it

public int currentScore;

Also in your block cs you can just call

GameStatus.instance.AddToScore();

No need to make reference at start

Upvotes: 1

Related Questions