Laser Defender - Score display singleton not working properly

I’m having a bizzare issue with the score display singleton in Laser Defender.
When I start my game from the start scene or play again from the game over
scene, the score does not update as I kill enemies but it is being calculated
correctly because when I die, I get the correct final score in the game over
scene. However, when I start my game from the game scene, the score DOES
update properly but does not carry over to the game over scene, the final
score is always 0. I’m not getting any errors. I have ScoreDisplay.cs attached
to a Score Text within Game Canvas in both my Game and Game Over scenes and
GameSession.cs attached to a Game Session object in both scenes as well. Any
idea what is happening here?

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

public class ScoreDisplay : MonoBehaviour
{
	Text scoreText;
	GameSession gameSession;
	
    // Start is called before the first frame update
    void Start()
    {
	    scoreText = GetComponent<Text>();
	    gameSession = FindObjectOfType<GameSession>();
    }

    // Update is called once per frame
    void Update()
    {
	    scoreText.text = gameSession.GetScore().ToString();
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameSession : MonoBehaviour
{
	int score = 0;
	
	private void Awake()
	{
		SetUpSingleton();
	}
	
	private void SetUpSingleton()
	{
		int numberGameSessions = FindObjectsOfType<GameSession>().Length;
		if(numberGameSessions > 1)
		{
			Destroy(gameObject);
		}
		else
		{
			DontDestroyOnLoad(gameObject);	
		}
	}
	
	public int GetScore()
	{
		return score;
	}
	
	public void AddToScore(int scoreValue)
	{
		score += scoreValue;
	}
	
	public void ResetGame()
	{
		Destroy(gameObject);
	}
}





GameSessionPrefab

Hi Mia,

Check if your “singleton” calls gameObject.SetActive(false); in the same if-block where Destroy(gameObject); gets called. If there isn’t that line of code, add it.

Did this fix it?


See also:

I re-watched video 115 and it turns out I didn’t need Game Session in the Game Over Scene in the first place. Also added the line you suggested as well as FindObjectOfType().ResetGame(); to LoadGame(). It’s all working now! Thanks a lot for your help!

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

Privacy & Terms