Use DontDestroyOnLoad to overwrite once it hits a specific scene

So right now I have an inventory script that is accessed through on a pop-up on the UI in most scenes. I am trying to use a basic DontDestroyOnLoad script that’s called in Awake() but it just takes the first instance from my map scene and duplicates it. And since I have a Map scene that has an empty inventory to start the game, that doesn’t work very well.


What is the best way to keep the current version of a gameObject, unless I’ve encountered a specific scene, in which case it overwrites and uses that one moving forward (and then continues to do that each time a certain type of scene is loaded thereafter)?


What would happen is, at the end of a scene you would get an item reward, and then that item would persist in my inventory through to the next scene, and if I found another item and picked it up, it would continue to add to it. It’s possible I’m doing this inefficiently to begin with, but I don’t want to use PlayerPrefs for this, and since I’m only saving data between scenes in a current session, I thought utilizing DontDestroy would be the simplest avenue.

Hi @awiesbrock,

You can use Singleton to do this. That prevents you from duplicating GameObjects with this kind of scripts. When you reach your scene, this example will destroy old GameObject and assign a new one.

public class Example : MonoBehaviour
 {
	public static Example instance;
	public bool isSpecificScene;

	void Awake ()
	{
		if (isSpecificScene && instance)
		{
			Destroy(instance.gameObject);
			instance = null;
		}

		if (instance == null)
		{
			instance = this;
			DontDestroyOnLoad(gameObject);
		}
		else
		{
			Destroy(gameObject);
		}
	}
}

All the best,

The Knights of Unity