Transfer data throughout scenes

I have no idea what I’m doing anymore, I have a GameObject that has a script attatched to it that handles everything for the mobile game I’m developing, and when the player dies he’s sent to another scene (The GameOver scene) which has a menu.

My brother is, this Menu is supposed to get the Score from the GameManager GameObject in Scene1, so I was told to try something like this

    void Awake()
    {
       DontDestroyOnLoad (this);
    }

This, er… Works, for a minute.

You play the game once, and it’s all fine and dandy, but then you back to the game and all of a sudden multiple game managers are running. After playing 3-4 times, you have almost 5 game managers running in each scene and they just keep stacking up.

Not only does this cause errors, and a ridiculous amount of memory usage… it also breaks the whole point of referencing.

Hello!

Yes, every time the scene is loaded, you’ll have the previous GameObject that isn’t destroyed plus a new one that was existing in the freshly loaded scene.

We handle this two ways.

  1. We have an Init scene where we put all our DontDestroyOnLoad objects. Actual gameplay is in a separate scene. This way we can reload the gameplay scene without reloading GameObjects we want to have a long lifetime.
  2. Make it a MonoBehaviour singleton. Or, just check to see if an existing object is already in the scene and destroy the newly loaded object.

Thanks! I actually just thought about doing the first solution provided, reading your answer assured me it would work. Thanks again!

The disadvantage of using solution 1 is that if you just hit play in the editor on a scene that isn’t the init scene then those objects won’t exist. Solution 2 is easier to start from anywhere

At my work we have the benefit of having done a few games and so our codebase is a bit built up.

We have a scene controller that manages the initialization of each scene. These all derive from a base class that automatically checks a static boolean “AppStarted” on our AppController class. If our Init scene hasn’t run, our scene controller will automatically load the Init scene on Awake instead of booting up the current scene.

The Init Scene sets AppStarted to true, so the rest of our scenes will load normally after that.