DontDestroyOnLoad duplicates GameObjects

Hello.

I have a strange problem with DontDestroyOnLoad.
I have some kind of map as a starting scene. From there there user can click on certain map-objects and a new level is loaded with Application.LoadLevel(). When the level is finished the map is loaded again.

I have a prefab for my global data. It is a hierarchy of several GameManagers und DataObjects that are needed in every scene. The hierarchy looks like this in design-time:
54720-001.jpg

The root GameObject ‘GlobalData’ has a script attached that calls DontDestroyOnLoad:

using UnityEngine;
using System.Collections;

public class GlobalData : MonoBehaviour 
{
	void Awake()
	{
		DontDestroyOnLoad(this.gameObject);
	}
}

As far as I understood the docs all child gameobjects should not be destroyed, too.

After starting the game and playing some levels (with jumping back to the map) the hierachy looks like this during runtime:
54721-003.jpg

Somehow the prefab is added again and again but the manager-objects are missing.

Another issue is that DontDestroyOnLoad does not seem to work in general as when I’m doing some debug prints the Start and Awake methods of my manager-objects are called for every scene.

Has anybody an idea what is going wrong here?

The problem is that you are loading a scene with that object in. If I am not mistaken, for example:

  1. Scene 1 - Have your data object
  2. You click and load Scene 2
  3. You go back to Scene 1
  4. Duplicated data object because Scene 1 has your data object

You might want to try using Singleton. A simple implementation

public class CharacterManager : MonoBehaviour
{
    public static CharacterManager instance;
    
    void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(this.gameObject);
            return;
        }
    }
}

Hope this helps.

perhaps you can use this.

public void Awake()
     {
         DontDestroyOnLoad(this);
 
         if (FindObjectsOfType(GetType()).Length > 1)
         {
             Destroy(gameObject);
         }
     }

if there are more than one existing objects of this type, then it will destroy the other… search singletons and you can find a lot of stuff on this.

hope this helps.

Here is the workaround I use all the time:

My first scene is called “Loader” - it contains all the persistent (dontdestroyonload) gameobjects for my game.

The only thing it does is load the main menu. Since I never return to this scene, no duplicates.