DontDestroyOnLoad & Singleton

Hi, in my 2D game i’m trying to use the same list of gameobjects for every scene with this code:

public class GameManager : MonoBehaviour
{
    public static GameManager instance;
    public static GameObject cities;
    public static List<GameObject> citiesList = new List<GameObject>();

    void Awake()
    {
        cities = GameObject.Find("Cities");

        if (instance != null)
            Destroy(cities);
        else
        {
            instance = this;
            citiesList.AddRange(GameObject.FindGameObjectsWithTag("City")); //Children of Cities
            DontDestroyOnLoad(cities);
        }
    }
}

With this method the game object “Cities” is duplicated in each scene. How can i avoid this?

Thanks!

Every time you load a new scene, your GameManager will be destroyed, because you only set “cities” to be permanent. Therefore, instance will always be null in Awake. The condition should be

if (citiesList.Count > 0)
    Destroy(cities);

to check if you already have objects stored. Or you could add a line, making the GameManager permanent too. Then you’d have to delete the new instance like Mateo showed.

public class GameManager : MonoBehaviour
{
public static GameManager instance;
public static GameObject cities;
public static List citiesList = new List();

     void Awake()
     {
         cities = GameObject.Find("Cities");
 
         if (instance != null && instance != this)
             Destroy(this.gameObject);
         else
         {
             instance = this;
             citiesList.AddRange(GameObject.FindGameObjectsWithTag("City")); //Children of Cities
             DontDestroyOnLoad(cities);
         }
     }
 }