2
votes

I have a main menu for a game where you can select difficulties, easy, normal etc. Currently, I load a separate scene for each difficulty, I have a scene for easy, a scene for normal, hard, etc.

I know you can pass variables between scenes, such as

something.GetComponent<someScript>().someVariable

But how do you pass a variable to a script on a GameObject that doesn't exist yet?

2

2 Answers

3
votes

You could use PlayerPrefs to solve this issue. For example, in your script on your main menu where the difficulty is set you would say:

PlayerPrefs.SetString("Difficulty", "Medium");

Then in your next scene, when you need to access that variable on a different script, simply use:

String difficulty = PlayerPrefs.GetString("Difficulty");

You could also look at using DontDestroyOnLoad to keep track of your variables on a persistent script which stays with you on an object that remains loaded even as scenes change. Then you could access the variables you need similar to how you have already described.

3
votes

To have the variable available in the next scene, the standard way is to have a game object that doesn't get destroyed when the scene changes. You do this by calling DontDestroyOnload() in any script on that game object, e.g.

void Awake () {
    DonDestroyOnLoad(gameObject);
}

You can use an existing game object or create one just for this purpose, with a single script that calls DontDestroyOnload() and also has variables that you want to pass to the next scene. You can set the variables, before loading the next scene, like in your example code:

someGameObject.GetComponent<GameVariablesScript>().someVariable = someValue;