- Home /
,DontDestroyOnLoad Object spawns endlessly
I have a first scene, where are created a canvas and a Game manager, both are DontDestroyOnLoad objects. When I go to the second scene everything is fine; However when I try to come back to the first scene, the game freezes at the first frame, before it even starts, and I have in the Hierarchy Panel : - FirstSceneName (even tho it is supposed to be unloaded at the scene change, no?) - FirstSceneName (is loading) - DontDestroyOnLoad
The two objects are "singletons". When I look at the list of DontDestroyOnLoad objects, I see that it keeps creating those objects endlessly, but they keep getting destroyed because there is already another one in the game. But they keep getting created anyway... Here is the code on the gameManager, the UI basically have the same one :
private static GameObject instance;
DontDestroyOnLoad(gameObject);
if (instance == null)
{
instance = gameObject;
}
else
{
Destroy(gameObject);
}
Also I am not experienced at all in Unity, so sorry if I used uncorrectly any vocabulary or explained poorly. Why does Unity keep trying to spawn the gameManager and the Canvas? Shouldn't it stop trying to after the first try?
Answer by SteenPetersen · Jun 02, 2020 at 06:17 AM
I would try to use singleton pattern this way:
public class SomeClass : MonoBehaviour {
private static SomeClass _instance;
public static SomeClass Instance { get { return _instance; } }
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(this.gameObject);
} else {
_instance = this;
}
}
}
Taken from this discussion on stackoverflow.