How to ScenePersist from level to level?

We made a ScenePersist object and script in one of the last videos for Tilevania so the game would remember pickups when the player hits something and goes back to the beginning of the level. The ScenePersist object destroys itself if there’s more than one or if the scene changes. That works great on level 1, but all of the pickups disappear on level 2. Rick only tested his on one level and so avoided this
little game-breaking problem. I’ll share my script but it is identical to Rick’s. Am I overlooking something?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class ScenePersist : MonoBehaviour
{
	int startingSceneIndex;
	
	void Awake()
	{
		int numScenePersists = FindObjectsOfType<ScenePersist>().Length;
		if (numScenePersists > 1)
		{
			Destroy(gameObject);
		}
		else
		{
			DontDestroyOnLoad(gameObject);
		}
	}
	
    // Start is called before the first frame update
    void Start()
    {
	    startingSceneIndex = SceneManager.GetActiveScene().buildIndex;
    }

    // Update is called once per frame
    void Update()
    {
	    if(SceneManager.GetActiveScene().buildIndex != startingSceneIndex)
	    {
	    	Destroy(gameObject);
	    }
    }
}

Hi Mia,

There is a bug in the current solution. You could test this fix:

public class ScenePersist : MonoBehaviour
{
    static ScenePersist instance = null;

    int startingSceneIndex;

    void Start()
    {
        if (!instance)
        {
            instance = this;
            SceneManager.sceneLoaded += OnSceneLoaded;
            startingSceneIndex = SceneManager.GetActiveScene().buildIndex;
            DontDestroyOnLoad(gameObject);
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }
    }

    void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        if (startingSceneIndex != SceneManager.GetActiveScene().buildIndex)
        {
            instance = null;
            SceneManager.sceneLoaded -= OnSceneLoaded;
            Destroy(gameObject);
        }
    }
}

Did this work for you?


See also:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms