How to reference data between scenes
Hi! I have two scenes, a "menu" and a "dungeon". In the menu the player can select a race and a class. I want to be able to reference what class was selected in order to instanciate the correct class prefab. I poked around a little bit, and quickly realized that there are many ways to go about this. Would any of you have a standard or recommended way to go about exchanging data between scenes and between sessions? Ideally without (what I think might be) abusing playerprefs.
Answer by BradyIrv · Jun 06, 2019 at 05:55 PM
1) Between scenes: static variables, DontDestroyOnLoad content or save data. 2) Between sessions: save data.
Okay. Does a script with a static variable need to be attached to a game object, or can I reference it from the file system?
Static variables, once initialized, are shared across all instances of the class and it doesn't have to be attached to a gameobject in the scene.
Be careful if you set a static variable to an object that can be destroyed. The next time you try to reference it on a different scene will return a null reference.
How do you initialize a static variable without a game object? Just leave the script in "assets" and drag-and-drop it as a reference into whatever script will be passing it static values?
It doesn't have to be initialized without a GameObject. But, you could use a static method to initialize it:
public static int = Init();
private static int Init()
{
return 0;
}
But, for what you're doing I think the preferred method would be to create a Game$$anonymous$$anager.cs or GameData.cs script and have it as a singleton instance. And then to add the DontDestroyOnLoad() property so that it carries from one scene to another. This will have to be attached to an object in the scene. AND this will only handle the current session, you would have to add Save/Load data if you want to have the class be persistent on the next session.
public class GameData : $$anonymous$$onoBehaviour
{
public static GameData Instance;
// Any data you want this script to have
public GameObject playerPrefab;
public string className;
public int characterLevel;
// initialize the Singleton instance
private void Awake()
{
if(Instance == null)
{
Instance = this;
// Carry over from one scene to the next
DontDestroyOnLoad(Instance.gameObject);
}
}
}
Note for future generations: found really good save/ load information here: https://www.sitepoint.com/saving-and-loading-player-game-data-in-unity/
Your answer
Follow this Question
Related Questions
A Little Help With Player Prefs 0 Answers
Save coins/currency? 2 Answers
How can I save this objects ? 0 Answers
Saving last runs score, only adds the previous score to it. 0 Answers
Application.persistentDataPath 0 Answers