DontDestroyOnLoad() problem

I wrote a script that changes the level once the player collected all the cubes, because when loading a new scene destroys everything from the previous scene I was told I need to use DontDestroyOnLoad()
I put this script inside an Empty GameObject in every scene but it doesn’t work:

using UnityEngine;
using System.Collections;

public class SaveForOtherScenes : MonoBehaviour {

    private LevelUpdater LU;

    void Awake()
    {
        LU = GetComponent<LevelUpdater>();
        DontDestroyOnLoad(LU); //Don't destroy the "Level Updater" script
    }

}

This is the updater:

using UnityEngine;
using System.Collections;

public class LevelUpdater : MonoBehaviour {

    private int LevelToLoad = 0; //This is the variable that determines which level will be loaded but it keeps reseting
    private CollectPickups HaveEnoughToContinue;
    private GameObject[] HowManyNeededToContinue;

    void Start()
    {
        HowManyNeededToContinue = GameObject.FindGameObjectsWithTag("PickUp");
        HaveEnoughToContinue = GetComponent<CollectPickups>();
    }

    void FixedUpdate()
    {
        if(HaveEnoughToContinue.HowManyCollected >= HowManyNeededToContinue.Length)
        {
            LevelToLoad ++;
            Application.LoadLevel(LevelToLoad);
        }
    }

}

Because the LevelToLoad variable keeps reseting to 0 the only levels I can play are 0 and 1 (1 and 2). Level 0 can be played once (the way it should be) and level 1 is repeated.

Put a script on the levelupdater that has DontDestroyOnLoad(this.gameObject);

1 Like

Try using static variables. The value should stay the same on scene change.