DontDestroyOnLoad Duplicating Objects When Scene Reloaded

I’m aware this is a generic issue, but i’m having trouble understanding.
When I reload my scene, I want to keep an object because it has previous time records. When the scene reloads, the object is kept, but another one is created because the scene has reloaded.
How do I prevent this?

The two most basic Unity-esque Singleton-like approaches look similar to this:

public class MyBehaviour : MonoBehaviour
{
	static MyBehaviour instance;

	void Awake()
	{
		if(instance == null)
		{	
			instance = this; // In first scene, make us the singleton.
			DontDestroyOnLoad(gameObject);
		}
		else if(instance != this)
			Destroy(gameObject); // On reload, singleton already set, so destroy duplicate.
	} 
}

public class MyBehaviour : MonoBehaviour
{
	static MyBehaviour instance;

	public MyBehaviour GetInstance()
	{
		if(instance == null)
		{
			// Something similar to this to load and create the object when needed.
			Object prefab = Resources.Load("Path/To/Prefab"); // Look up the docs ;)
			GameObject go = Instantiate(prefab);
			instance = GetComponent<MyBehaviour>();
			DontDestroyOnLoad(go);
		}
		return instance;
	} 
}

(my apologies, if there’s an error, this is typed without a compiler)

You can either place your object in the scene, assign it to some persistent storage (usually a static variable for the lifetime of your app) and then destroy other duplicates, when you load a new scene.

The other approach is to only load and create the singleton object, when it is needed.

And as always the warning: Singletons are called dangerous or frowned upon by many developers, because they attract bad design decisions, especially in Unity and might cause bugs related to the static instance.

  • static variables are not garbage collected, you have to manage their lifetime yourself and set it to null, if you want the object to be freed from memory
  • there are typical mistakes, where you end up with duplicate instances of you intended singleton or leftover instances, which you don’t want anymore (imagine a round-based fighting game, where the score manager still has a score from the last round and things like that)
  • singletons invite other code to just call it easily without a reference to it, creating lots of dependencies to this once class, which then might change and cause lots of cascading errors or lots of code changes

On the other hand, there’s nothing wrong in using them correctly.