I have a trigger that causes an event that’s only supposed to happen once, when the level first loads. I never want it to happen again. When I tell it not to destroy when another level loads and then disable it, Unity makes a copy of the gameObject next time I load the first level and the event happens again. How can I keep this from happening?
Whenever a scene is loaded unity makes an instance of all objects in a scene, so if a scene has an object marked as “don’t destroy on load” and the scene is loaded multible times, you get multible copies of the object. To avoid this you can do the following (c#):
public class MySingleton {
private static MySingleton instance;
void Awake() {
if (instance != null instance != this) //IF we already has an instance of this class
Destroy(gameObject);
else {
instance = this;
DontDestroyOnLoad(this);
}
}
}
Another way is to put all global manager objects into Scene 0 and nothing else into that scene. Once scene 0 is loaded immediatly load the first actual scene and never reload scene 0.
Works nicely. Thanks!