When I do DontDestroyOnLoad(gameObject) in a scene and then revisit the scene I see a duplicate game object as well. How can I prevent this?

I do something like this with my GameManagers when i need them to move along to another scene but can’t have 2 Game Managers running.

GameManager gM;
   
void Start(){
   if (gM != null) // Means there is already a GameManager in the scene, this one is not needed
	{
		Destroy (this.gameObject);
	}else // There hasn't been a Game Manager assigned yet so assign this one
	{
		gM = this;
		DontDestroyOnLoad (this.gameObject);
	}
}

I hope it helps

I assume by revisit, you mean, closed the scene and went back to it during runtime -
Are you using loadsceneadditive?

Maybe have a script, which is dontdestroyonload, that ensures your dontdestroyonload object is only created with the scene starting, if that object is checked and null.

It may be best to create the DontDestroyOnLoad object using script.

Check to see if it already exists, then if it doesn’t, create a instance of it from a prefab (using GameObject.Instantiate ).

If you’re using this object to store game-state information, there’s a major benefit to using it this way - you can put the creation script in every scene and you’ll be able to test each scene individually. Otherwise, many of your scenes won’t have the DontDestroyOnLoad object available when testing.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyScript : MonoBehaviour {
public static MyScript Instance;

	void Awake()
	{
		if (Instance == false) {
			Instance = this;
		
		}
		else {
			Destroy (this.gameObject);
		}
		DontDestroyOnLoad (this);
	}

Hope this may help you.Nsks

The Unity team actually has a helpful tutorial that encompasses this. If you watch the DisplayManager tutorial, or the generic modal window, you’ll see how to accomplish it. Also, you’ll get a handy bit of assets for your library.