0

I have a StartupScript that i want to run every time when a scene (re)loads.

When I load Scene 1 the script runs.
When I load Scene 2 the script runs.
When I go back to Scene 1 the script does not run.

How can i force the StartupScript to run every time the scene is loaded?

The script is present in each scene, on a prefab StartScriptHolder.

I'm looking at SceneManager: maybe by making and deleting named instances of Scenes I can force the StartupScript to be generated every time?
It seems very inefficient to create and discard complete Scenes just for the purpose of running a single script.

Rob G
  • 123
  • 3
  • 15
  • 2
    Please share your code ... it sounds like your `StartupScript` uses [`DontDestroyOnLoad`](https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html) or additive scene loading -> `Awake` and `Start` etc will not be called again. You can however simply attach a callback to [`SceneManager.sceneLoaded`](https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-sceneLoaded.html) – derHugo May 18 '21 at 07:27
  • Thanks for this advice. I did a bunch of debugging and found I had incorrectly declared some variables static. Undoing this fixed the issue. – Rob G May 19 '21 at 04:40

1 Answers1

1

I don't know how are you handling the swap between scenes. Have you tried using UnloadSceneAsync from SceneManager? (https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.UnloadSceneAsync.html)

I am working in a project where I have to do the same. I unload a scene and if I load it again, I need to run the Start function again.

    SceneManager.LoadScene("SceneName", LoadSceneMode.Additive); //Loading the new scene
    SceneManager.UnloadSceneAsync(val); // Unloading current scene

In this case what I am doing is load the new scene by its name and in additive mode (this is a requirement I have but you can load it using another mode. After that I use the function I suggest you tu use which needs as parameter the ID of the scene. You can find this ID in build settings window. BuildSettings Window

  • Thanks for this advice. I tried, it did not solve my issue but did help me find where I went wrong (I had incorrectly declared some variables static. Fixing this resolved the issue). – Rob G May 19 '21 at 04:43