- Home /
will switching scenes overwrite data?
So lets say we have a simple script and it adds +1 to an integer value everytime a key is pressed, then we put that data into a save file. Then we switch the scene to another scene, will the integer still have the value or the scene overwrites it?
Depends..
Value will be inaccessible, unless you load the value from your save file to new variable in the new scene (the original variable will be lost when scene is destroyed)
Variable will be inaccessible, unless the variable is as a member field of ScriptableObject (it is scene independent)
Variable will be lost, unless you set gameobject where the component and the variable is to the DontDestroyOnLoad
Answer by Mashimaro7 · Jan 23, 2021 at 12:58 PM
Unless your object is persistent, it will. There are a few work arounds, such as saving to player prefs and loading on the next scene, or making the values and the scripts static. Another way would be to put your game manager in a separate scene, load it in async, and have that scene persist throughout your game,
Answer by Llama_w_2Ls · Jan 23, 2021 at 04:44 PM
Advancing on one of Mashimaro7's suggestions:
Static classes don't need to be attached to a gameObject, which means they cannot be destroyed when switching scenes, but will be lost when you stop playing. For example:
public static class DontDestroyTheseValues
{
public static int Number;
}
No matter what scene you are in, if you write DontDestroyTheseValues.Number += ...
it won't switch back to its default number. Unfortunately, you cannot add MonoBehaviour to a static script. @greenklover
Your answer
Follow this Question
Related Questions
SceneManager onActiveSceneChange Pause for a while before loading a new scene 0 Answers
playerprefs 0 Answers
SceneManager.LoadScene not working with button 1 Answer
Scenes won't change when built 1 Answer
How Do I Link Different Scenes? 4 Answers