Keep a menu from scene to scene

While making a little point and click game in Unity, I was facing a problem.
How would I keep my UI menu consistent between scenes?

e.g. : I picked an object that laid on the ground in a scene and then go to another scene. I want my menu to still have it when the next scene is loaded.

A simple approach

What I really want is for my menu to be the same when the scene changes.
For this, Unity has a simple function : DontDestroyOnLoad( GameObject )

To use it is really simple, Just call it when the object is created, like in its Awake method, and there you go.

Here is the code from my UIController, a script that I attached to the canvas that contains my menu and inventory.

void Awake() {
  DontDestroyOnLoad (this.gameObject);
}

Now this canvas will not be destroyed when the scene changes but it will not prevent the loaded scene to create a new one. To do this we will simply destroy the new one if there already was one kept from another scene.

void Awake() {
  if (FindObjectsOfType(GetType()).Length>1) {
    Destroy (this.gameObject);
    return;
  }
  DontDestroyOnLoad (this.gameObject);
}

First we check if there is more than one object of the current type in the scene. If so, we need to destroy the new one. the old one will not call Awake() because it was already awoken in the first scene loaded so the one calling this method will be the new one. We can destroy it without problems and return because there is nothing more to do.

Doing this I can have a menu in each scene so they are easy to test but it will not cause problems when playing the game and going from scene to scene as the new menu will be destroyed automatically.

There might be a better way to do this but it’s simple and effective. Just one Find() when the scene loads should not be an issue.


Alternatively you could use this on you player and have it keeping track of the inventory. You could then check on scene load what is in the player’s inventory and populate the scene’s menu accordingly.