In my menu scene I have an empty GameObject that uses DontDestroyOnLoad to maintain variables between scene loads, but every time the menu scene is loaded another copy of it is created and maintained.
I know that I could add code to another script in the menu scene to check and see if the object exists and if it doesn’t instantiate a new one from a prefab, but I have a feeling that there should be functionality built into Unity to do this since the DontDestroyOnLoad function exists in the first place.
There is no such functionality. You can either have a “boot loader scene”, or you can write a simple check inside the Awake method of a “boot loader object”. The following snippet shows how you can create a boot loader that instantiates an object if it hasn’t already been instantiated. If you then make this BootLoader a prefab and have it in each scene, then you can rest assured that you will always get a prefab instantiated once. This prefab the boot loader instantiates could then hold your data.
public class BootLoader : MonoBehavior {
public GameObject prefab;
static Object instance;
void Awake () {
if (!instance) {
instance = Instantiate (prefab);
DontDestroyOnLoad (instance);
}
DestroyImmediate (gameObject);
}
}