so i have two button and i want when the user click any of the two button to load the same scene but with some change in variables
i am trying to use SceneManager.LoadScene(“test”); and than access an object in the scene and change an int in a script before loading the scene
and i don’t want to make another scene because it is not that different from each other
The easiest way to do this is to use a static variable that you set to the desired value just before loading the scene, then in the scene have a script that reads this variable in its Awake()
function. You can even change the script execution order of this script to make sure that it runs as the first thing.
EDIT: code example:
public class SceneLoader : MonoBehaviour {
// because it is a static variable, you don't need a game object to hold it, and it will "survive" loading levels
private static int differentiatingVariable = 0;
public static int GetDifferentiatingVariable () { return differentiatingVariable; }
public void OnButton0Clicked () {
differentiatingVariable = 0;
SceneManager.LoadLevel("level");
}
// similar code for button 1 clicked
}
// put this on a game object in your level scene
public class LevelSetup : MonoBehaviour {
private void Awake () {
int levelData = SceneLoader.GetDifferentiatingVariable();
// do here what you need to differentiate the level
}
}
A similar, but nicer and more general solution is to use a “LevelData” class that derives from ScriptableObject, and put all the variables that may change a level into it. You can instantiate and set up the level data, then assign it to a variable of a script that will not be destroyed when loading the new scene. Then it is the same thing, you load the scene, and use a script that reads the level data in its Awake()
and does the changes according to it (sorry, no code example for this, because it is a lot more complicated).