- Home /
DontDestroyOnLoad issue
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.
Answer by Statement · Oct 02, 2012 at 10:01 PM
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);
}
}
$$anonymous$$y first idea for a workaround was something similar to this but not quite as pretty, but ultimately I want to be 100% sure that the object is maintained and adding more code adds more potential for error.
The solution I'm going to use is to have the object instantiated in its own scene that plays a splash animation so it loads before the main menu, with no option to reload the splash screen so it is impossible for more than one instance to exist.
Thank you for your prompt help!
Your answer
![](https://koobas.hobune.stream/wayback/20220613081805im_/https://answers.unity.com/themes/thub/images/avi.jpg)