Hi guys, so I want to save and load the last loaded scene that I was in in my project, so when I click load it starts me in the scene I last saved in.
I already did this with Playerprefs
but I want to do it with Json. This is how I’ve done it until now:
my save:
void OnApplicationQuit()
{
PlayerPrefs.SetInt("SavedScene", SceneManager.GetActiveScene().buildIndex);
SaveGame();
}
from continue button in the menu:
public void OnContinueGameClicked()
{
DisableMenuButtons();
DataPersistenceManager.instance.SaveGame();
SceneManager.LoadSceneAsync(PlayerPrefs.GetInt("SavedScene"));
}
from my load save button:
public void OnSaveSlotClicked(SaveSlot saveSlot)
{
DisableMenuButtons(); DataPersistenceManager.instance.ChangeSelectedProfileId(saveSlot.GetProfileId());
if(!isLoadingGame)
{
DataPersistenceManager.instance.NewGame();
}
SceneManager.LoadSceneAsync(PlayerPrefs.GetInt("SavedScene"));
}
You can try to use a JSON package like Newtonsoft Json Unity Package | Newtonsoft Json | 3.0.2
One example on how to convert an object to and from JSON is in the documentation:
You can use the JSon utility. Create a class that stores data to be saved.
[System.Serializable]
public class SavedData
{
public static string path = Application.persistentDataPath + "/SaveData.json";
public int savedScene;
}
void SaveCurrentScene()
{
SavedData savedData = new SavedData ();
savedData.savedScene = SceneManager.GetActiveScene ().buildIndex;
string json = JsonUtility.ToJson (savedData);
System.IO.File.WriteAllText(SavedData.path, json);
}
void LoadLastScene()
{
string jsonData = System.IO.File.ReadAllText (SavedData.path);
SavedData savedData = JsonUtility.FromJson<SavedData> (jsonData);
SceneManager.LoadSceneAsync(savedData.savedScene);
}
I would recommend Newtonsoft’s JSON utility. I actually created a video tutorial on this should anyone find it helpful. You can store basically any kind of data, and it even has its own version of player prefs using JSON!