Scene Persist Problem Fixed

I think this code below for ScenePersist.cs is bad. I think I have it correct from the video lesson, but please correct me if I’m wrong - made quite a few changes to it in testing:

using UnityEngine;
using UnityEngine.SceneManagement;

public class ScenePersist : MonoBehaviour
{
    int startingSceneIndex;

    private void Awake()    // SINGLTON PATTERN:
    {
        int numScenePersist = FindObjectsOfType<ScenePersist>().Length;  
        if (numScenePersist > 1)
        {
            Destroy(gameObject);
        }
        else
        {
            DontDestroyOnLoad(gameObject);
        }
    }

    void Start()
    {
        startingSceneIndex = SceneManager.GetActiveScene().buildIndex;
    }

    void Update()
    {
        int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
        if (currentSceneIndex != startingSceneIndex)
        {
            Destroy(gameObject);
        }
    }
}

With the above code, from adding some Debug.Log statements, I determined that when the game goes to the next level, the new ScenePersist Game Object (with the Pickups Child Object, with the Coins Childed to it) that is in the new level, sees the old one from the previous level, and deletes itself in Awake (because there is 2 ScenePersist Game Objects). Then the old ScenePersist Game Object, in it’s Update function sees it is in a different scene and it deletes itself, too. This leaves no coins in the new level (and no ScenePersist Game Objects). When the Player dies, then the new level is reloaded, and it’s ScenePersist doesn’t delete itself, and the coins for the new level show up.

To fix this, in LevelExit.cs I added the 3rd line below, to destroy the old ScenePersist Game Object before loading the new level:

   IEnumerator LoadNextLevel()
    {
        yield return new WaitForSecondsRealtime(levelLoadDelay);
        Destroy(FindObjectOfType<ScenePersist>().gameObject);
        var currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
        SceneManager.LoadScene(currentSceneIndex + 1);
    }

Note, you could now remove the code from Update, but, for when the Player dies, you would have to delete the ScenePersist in ResetGameSession.
Hope this helps someone,
Jim

2 Likes

This is what I was looking for, thank you! Maybe it’s because it’s too late, but I could not figure out a solution. I figured out the problem, but I kept trying to just get the script to make a new starting scene int at the start of every scene and it became a nightmare. Have a good day!

1 Like

you’re a lifesaver

Privacy & Terms