- Home /
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!
Answer by Mateo03 · May 29, 2020 at 03:04 PM
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 && instance != this)
Destroy(this.gameObject);
else
{
instance = this;
citiesList.AddRange(GameObject.FindGameObjectsWithTag("City")); //Children of Cities
DontDestroyOnLoad(cities);
}
}
}
Try with this code. You should destroy the gameObject that isn't the instance (the duplicated one) in Awake.
Thanks, i tried this but i still have the same problem, the game object "Cities" is still duplicated.
I used a separate class for that specific object and now it works:
public class Cities$$anonymous$$anager : $$anonymous$$onoBehaviour
{
public static Cities$$anonymous$$anager instance;
void Awake()
{
if (instance != null && instance != this)
Destroy(this.gameObject);
else
{
instance = this;
DontDestroyOnLoad(this.gameObject);
}
}
}
Answer by viesc123 · May 29, 2020 at 05:08 PM
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.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Check to see if any bool instance is true? 1 Answer
2D Get Object Height to stack up on the screen 1 Answer
FindObjectOfType or FindWithTag 1 Answer