I have an object that holds some scripts that stay active between scenes. They persist between scenes using the “DontDestroyOnLoad” approach.
If I had a new instance of the script initializing in every scene I could just use Awake and Start. But since I am persisting them throughout scene transition and need them to call the method on every scene load rather than just the first scene the scripts are initialized in, is there any built-in way to invoke a method of a persisted script on a new scene load?
I have been looking at SceneManager.sceneLoaded but it says it can be used to get notifications when a scene is loaded and the examples only use Debug.
Can SceneManager.sceneLoaded be used for the purpose of calling methods on persisting gameobjects/scripts when a new scene is loaded?
If not is there something else? Or could someone point me in the right direction? Thank you in advance.
Pretty sure that’s what you want… hook it ONCE, and when the scene you consider the start of your game flow loads, zero out your game counters or whatever stuff you do.
1 Like
Worked like a charm. Was so much simpler than I had thought it would be. The only problem I ran into, in case anyone ever comes to this thread, is that it can break some things due to a change in execution order. Because the execution occurs during OnEnable, which occurs before Start. I had some things that broke because the new SceneManager.sceneLoaded event occurred before the start methods of the objects that were being operated on. So when I was accessing data structures in those objects, they were then being overwritten by the monobehavior script’s start method that used to actually initialize the data structure back when I had the operations all occurring in Start before I was using SceneManager.sceneLoaded because I had a local instance of the parent operating script in each scene using start to initiate the operations, but now I have a persisting instance that has the operation invoked by the SceneManager.sceneLoaded event. So I had to move the initialization to Awake, so that the objects’ data structures were initialized before the SceneManager.sceneLoaded is invoked during OnEnable, then everything worked flawlessly.
Thanks Kurt, I tried your tank game. The missile mechanic is surprisingly fun and refreshing.
1 Like