How do I access a variable from a different scene using C#?

So far I have two scenes in my game:

  1. the main menu scene
  2. the actual game scene

In the main menu screen I have a button which enables a type of game mode. If enabled, the player won’t be able to save the game (by disabling the save game script).

I want to know how do I access a Boolean in a script in the Main Menu scene from a script in my Game scene so that I can disable my save game script (C# only).

For example: In Main Menu scene I would have:

public static bool hardcoreMode;

void Awake ()
{
           //some code..

           hardcoreMode = false;

           //more code..
}

void OnGUI()
{
            //some code...
    
            if(GUILayout.Button("HardCore Mode"))
                    hardcoreMode = true;

             //more code...
}

So how do I access the Boolean “hardcoreMode” from a script in my Game scene?

(Beginner in Unity and scripting in general)

3 Answers

3

Use Singletone class

Would you make an example, please? Like I've mentioned, I am new to Unity and Scripting in general.

you can find more about singletons in following link : http://wiki.unity3d.com/index.php/Singleton

For a beginner like me, it's a bit confusing to use Singletons but thank you for your input. I just need to take a bit of time to understand it.

This seems like a setting you want to store throughout the game, including multiple play sessions, for which you can use PlayerPrefs. This is common practice for storing player/game data.

Thanks appreciate your help but its still not working. there are no compier error but it just doesn't work... any idea? Im beginner on this. And for some reason i cannot add the scrrenshot either....

I believe you could make you boolean a static variable by adding static in front of it, or have a manager game object with that variable and dontdestroyonload.

Dontdestroyonload Unity - Scripting API: Object.DontDestroyOnLoad

Static variable

I know how to use static variables since it's common for me to reference other scripts, but I only ever done that with variables and classes in the same scene. Will the value stay the same if I reference a variable from a different scene? like in my example code in the question. If I use DontDestroyOnLoad on an empty game object with my script attached to it, will that be an efficient way to achieve what I want? Or will it be better if I just go back to static variables if that works across different scenes like I have asked about before?

Make sure you use limited static variables else you may get performance issue. and make sure you use following code in ur script public static "YourScriptName" Instance; void Awake() { if (Instance == null) Instance = this; else if (Instance != this) { Destroy(gameObject); return; } DontDestroyOnLoad(this); } Or else you will end up will multiple game object when you reload the scenes