I have the following:
public class Singleton : MonoBehaviour
{
private static Singleton _instance = null;
public static Singleton Instance
{
get { return _instance; }
}
void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(gameObject);
return;
}
_instance = this;
DontDestroyOnLoad(gameObject);
}
}
I add the component to an Object (Transitions) expecting it will last for the next load, then when I load the next scene, my object is destroyed.
The GO Transition has another script attached and it’s children have another script attached.
Any ideas on why DontDestroyOnLoad is not working?
I was having the same issue as you and then I realized that my singleton was not a root GameObject and its parent was being destroyed, thus destroying it as a child…
To fix this instead did:
DontDestroyOnLoad(transform.root.gameObject);
which then introduced all kinds of problems with duplicate root objects, which I then had to merge all of the non-singleton objects together into under a single singleton root. Kind of a pain, but in the end it was worth it for a nested singleton.
What worked for me was, that I moved it to root on awake the first time. So I could leave it nested in my prefab.
void Awake()
{
if (instance != null && instance != this)
{
Destroy(this.gameObject);
return;
}
else
{
// just move it to the root
this.transform.parent = null;
instance = this;
this.LoadAd();
}
DontDestroyOnLoad(this.gameObject);
}
I didnt quite understood the logic behind defining a singleton MonoBehavior class. What do you gain by making it singleton?
why not just do DontDestroyOnLoad(gameObject) inside Awake() and then use GameObject.Find(“singleton”).GetComponent()?
In line with the answer by sotirosn, in my case it was even simpler: The only thing I needed to do was move the object to not be nested under any other game object. Just make sure it’s right under the scene. It then worked as expected. It’s pretty incredible how this isn’t even mentioned in the documentation. DontDestroyOnLoad does NOT work unless the object in question is not under any other object.