- Home /
How to make Advanced save and Load Files?
The other post i made crashed or something and i wrote a lot, so this one is going to be shorter...
I've noticed that some games have really nice additions to their save and load files. Like, Time and Date when you saved the game. The In-Game Time and Date when you saved. The Area you were in when you saved. A popup that says "Yes or No" and asking you if your sure you want to load this save file. The Total Amount of Playtime, ect.
I'm currently working on a Fantasy RPG, and i would like for my load files to have these features. Can Anyone help me do this? Thanks!
Here is a example of what i mean, taken from the game Pokemon Emerald. https://cdn.bulbagarden.net/upload/thumb/3/3f/Save_USUM.png/300px-Save_USUM.png
Although that picture was for saving the game, i would like something like it for loading the game.
Answer by TheKnightsofUnity · Jul 19, 2018 at 02:51 PM
Greetings friend!
I would recommend serializing a class or several classes into JSON and save it in player prefs. It is a comfortable way as long as you won't have to serialize thousand of fields. When it comes to data you'd like to save like playtime you need to track itt all the time in separate classes with some public accessor.
I can present you some basic code that contains Save and Load methods so you'll have an overview of what's going on.
[System.Serializable]
public class SaveRecord
{
public DateTime SaveTime;
public long TotalPlayTime;
public PokemonListWrapper PokemonCollection;
public static SaveRecord Record(int saveIndex, long playTime, List<Pokemon> pokemonCollection)
{
var save = Load(saveIndex);
save.SaveTime = DateTime.Now;
save.TotalPlayTime = playTime;
save.PokemonCollection = new PokemonListWrapper(pokemonCollection);
save.SaveToPrefs(saveIndex);
return save;
}
private void SaveToPrefs(int saveIndex = 0)
{
string jsonString = JsonUtility.ToJson(this);
PlayerPrefs.SetString("game_save_" + saveIndex, jsonString);
PlayerPrefs.Save();
}
public static SaveRecord Load(int saveIndex)
{
return JsonUtility.FromJson<SaveRecord>
(PlayerPrefs.GetString("game_save_" + saveIndex, "{}"));
}
}
[System.Serializable]
public class PokemonListWrapper
{
public List<Pokemon> PokemonList;
public PokemonListWrapper(List<Pokemon> list)
{
PokemonList = list;
}
}
public class Pokemon
{
}
You may wonder what the PokemonListWrapper
is. Actually Unity built-in JsonUtility
can't handle serializing Lists so we need to write our own list wrapper. I assumed you don't need any help about the UI part, but if you have any questions please ask :)