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:
Question: How can I keep that script inactive while loading scenes and active while playing?

you can do it with
.enabledsee unity doc.if you have access to your player object you can deactivate
DontDestroycomponent with something like this:and activating it with setting it
trueor you can use singleton design pattern for your player. something like this:
this will destroy every duplicated Player object
you can use these simple scripts too.