How to avoid duplicate while reloading the scene in Unity?

47 Views Asked by At

I'm creating a 2D Unity game with multiple scenes. Now, I'm trying to add a restart button.

I'm using the code below to move the player from one scene to another without destroying the player:

DontDestroyOnLoad(gameObject);

And the following code to reload every scene:

int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;

// Reload all scenes
for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
{
    SceneManager.LoadScene(i, LoadSceneMode.Single);
}

// Load the scene that was active before restart
SceneManager.LoadScene(currentSceneIndex);
SceneManager.LoadScene("floor1", LoadSceneMode.Additive);
SceneManager.LoadScene("starter scene", LoadSceneMode.Additive);

If I deactivate the script component which contains the DontDestroyOnLoad function, it works well for one scene.

Just a image of script with deactive for better understanding:

image

Question: How can I keep that script inactive while loading scenes and active while playing?

1

There are 1 best solutions below

1
Noobogami On

you can do it with .enabled see unity doc.
if you have access to your player object you can deactivate DontDestroy component with something like this:

var dontDestroyComponent = playerObject.GetComponent<DontDestroy>();
dontDestroyComponent.enabled = false;

and activating it with setting it true


or you can use singleton design pattern for your player. something like this:

private static Player _instance;
private virtual void Awake()
{
    if (_instance == null)
    {
        _instance = this;
        DontDestroyOnLoad(gameObject);
    }
    else if (!Equals(this, _instance))
    {
        Destroy(gameObject);
    }
}
private virtual void OnDestroy()
{
    if (Equals(this, _instance))
    {
        _instance = null;
    }
}

this will destroy every duplicated Player object
you can use these simple scripts too.