Home > Enterprise >  Data Persistence between Scenes in Unity creates multiple instances, regardless of conditional destr
Data Persistence between Scenes in Unity creates multiple instances, regardless of conditional destr

Time:12-10

I am creating a game where the first scene will have a generated map saved as a 2D array, then the next scene takes care of all the combat. Once that's done, user needs to go back to the first scene and see the same map. I have followed Unity's tutorial on Data persistence, and as you can see in the code below I am checking twice if an Instance is not null and destroying the object if its not.

The problem is, that every time I go back from combat scene to the map scene, it creates another instance of WorldMapManager, and generates another map on top of the existing one.

Where am I going wrong to stop creation of unnecessary extra copies of WorldMapManager object?

public class WorldMapManager : MonoBehaviour
{
    public static WorldMapManager Instance { get; private set; }
    public static int _mapSizeX = 4;
    public static int _mapSizeY = 4;
    public static int _playerScore;
    public static int _playerCells;
    public static int _enemyScore;
    public static int _enemyCells;
    public static GameObject[,] _map;
    public static GameObject _startingPoint;
    public static Vector2Int _playerBase;

    // Awake is called before Start
    void Awake()
    {
        if (WorldMapManager.Instance != null)
        {
            Destroy(gameObject);
        }
        else
        {
            DontDestroyOnLoad(gameObject);
        }
        SceneManager.sceneLoaded  = OnLevelFinishedLoading;
    }

    // Initialize the map
    public void InitMap()
    {
        // Map Generation happens here
    }

    // OnSceneLoaded is called when a scene is loaded
    void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode)
    {
        if (scene.name == "WorldMap")
        {   
            if (WorldMapManager.Instance != null)
            {
                Destroy(this);
            } else
            {
                InitMap();
            }
        }
    }
}

I have been stuck on this for several days trying different approaches, but I'm all out of ideas, so thank you very much for any help.

CodePudding user response:

By the looks of your code it seems you never ever set the WorldMapManager.Instance. So it will always be null and always go on to DontDestroyOnLoad(gameObject);.

So add the assignment to Instance too.

Instance = this;
DontDestroyOnLoad(gameObject);

For the same reason in void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode) the InitMap() will be executed. No need to set anything to Instance here ofcourse.

  • Related