UI Menus and Multiple Scenes - Pass variables?

Hey guys,

I’m an artist so don’t do much programming, but I’m stuck on what I believe is a simple problem. I’ve spent the morning reading up on static variables vs. dontdestroy vs. singleton, and I feel like my head is going to explode.

So anyway I have a simple intro menu that loads when the game starts. Upon closing that, I add a simple button in the corner that just shows the menu again. When the user jumps to a different scene, I just want that “state” to be correct, so when they come back they would see the minimized menu button, not the initial full screen menu.

At first I felt like this would be so simple, but with every technique and post I read, I just confuse myself more and more.

So what’s the easiest method to achieve this? (I don’t want to use PlayerPrefs because I do want the initial screen when they reload the game) It’s a UI button that will ultimately “set” that scene state, since closing that is what bring up the smaller menu button.

Thanks, any help would be appreciated…

The best option is to store your menu state in a static class variable which will persist as long as your game is running.

When the menu is closed, set PersistentGameState.showMenu = false
When the menu is opened, set PersistentGameState.showMenu = true

When the scene changes, the menu object will be reset as usual and you can use the showMenu state to determine if you should display the menu or hide it.

something like…
PersistentGameState.cs

public static class PersistentGameState {
    public static bool showMenu = true; // initially the menu should be displayed
}

MenuState.cs (attach this to your menu object)

using UnityEngine;

public class MenuState : MonoBehaviour {

    private void Start() {
        // when the scene is loaded, restore the persistent menu state
        DisplayMenu( PersistentGameState.showMenu );
    }

    public void DisplayMenu( bool state) {
        PersistentGameState.showMenu = state;
        this.gameObject.SetActive( state );
    }

}

From your ‘open menu’ UI button, you can hook up the OnClick event to the Menu object’s MenuState->DisplayMenu() method. Make sure that you check the box for the OnClick parameters so that it is calling DisplayMenu(true). If you have a ‘close menu’ button, you would have it hooked up to call DisplayMenu(false).