- Home /
DontDestroyOnLoad still destroys object
I am creating a singleton inside Awake in order to keep one Game Session object at every scene. I am using DontDestroyOnLoad , but it doesn't seem to work. When I load into the next scene. Game Session gets destroyed and I lose all the data stored inside it. Here is my code : using UnityEngine;
public class GameSession : MonoBehaviour
{
int score = 0;
private void Awake()
{
SetUpSingleton();
}
private void SetUpSingleton()
{
int numberGameSessions = FindObjectsOfType<GameSession>().Length;
if (numberGameSessions > 1)
{
gameObject.SetActive(false);
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}
I check if there already is another Game Session object and if there is I destroy it. This is so that it keeps the original Game Session and not to reset the data that is stored inside it. Any help is greatly appreciated.
Answer by dacarrera · Mar 26, 2020 at 05:35 AM
A few things, without getting too deep into whether a Singleton is even necessary here:
With this setup, you're forced to include a GameSession GO in each of your scenes that want to use it, even if 99% of the time it'll be carried over from a previous scene.
This isn't how a Singleton should be implemented.
You're inheriting from MonoBehaviour without making use of it (aside from wanting the object alive in each of your scenes).
Singleton is a design pattern, so try not to think of it as "I'm creating a Singleton in Awake()" and rather that you're implementing a pattern that guarantees your object is unique and thread-safe. If you're just keeping track of int score
, and want to use the Singleton pattern, you should do it directly instead of half-baking it with DontDestroyOnLoad()
. Here's a quick implementation:
// Thread-safe singleton implementation with lazy instantiation
// You can throw your score field in here, and access it with GameSession.Instance.score
public sealed class GameSession
{
private static readonly GameSession instance = new GameSession();
static GameSession() { }
private GameSession() { }
public static GameSession Instance
{
get
{
return instance;
}
}
}
When you implement it this way, you get rid of the unnecessary reliance on MonoBehaviour, you guarantee one unique object, and you'll be able to access your score Just by calling GameSession.Instance.score
without worrying if there are multiple copies alive.
Answer by KChatzis06 · Mar 26, 2020 at 02:16 PM
@dacarrera Thanks a lot for the explanation. I will try to figure out how to use this way of implementing singletons. And one more question: for this to work, what namespaces do I have to be using?
Your answer
Follow this Question
Related Questions
How to stop duplicates from dontdestroyonload 1 Answer
Animator destroyed on DontDestroyOnLoad 2 Answers
How to make a saved score destroy on load new scene 0 Answers
"Dont destroy on load" does not work at forst 2 Answers
Object.DontDestroyOnLoad ? 2 Answers