Rookie Mistakes I - Unity Scene Switching
The start of a small catalogue of things that caught me out while learning about UI and Data Persistence from here
GameObjects with DontDestroyOnLoad survive scene switches. Inspector References to them Do Not.
Singletons are useful. It seems to be typical to define a long lived singleton game object like this, to help you manage state.
You create an empty in your initial scene, attach this singleton GameManager (or whatever you called it) as a component.
In your Awake/Start method you make sure that the object will live across scene changes, and you’ll end up with something like this:
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
LoadScore();
}Which is great! You now have an object that is accessible with out running something like GameObject find methods in your Start() etc.
Buttons and such
Now let’s say you’ve added a button and want to add an OnClick via the inspector. Your GameManager is already there so you decide to reference it and choose a method:

In my case I had a quit game method. Seemed to make sense for it to be in here. However, when I switched from my Menu scene to my Game scene and back again, the reference was lost!
In order to stick with this approach of configuring via the inspector, we need to create something that lives in the scene. So I made a Scene level UI script, attached it to an empty, and referenced that instead. It’s Exit() method just calls the Original Manager method, which can still be accessed via the code.
