I made a Json save system for my Unity game. I wanted to make something as generic as possible to keep the code DRY. I couldn't find much information online on how to make something generic.
Could you guys let me know what do you think of it?
So first, I have this utils class to save and load json data.
public class JsonDataManagement
{
private static string GetPath(string fileName)
{
return Application.persistentDataPath + Path.AltDirectorySeparatorChar + fileName;
}
public static void SaveData<T>(string fileName, T data)
{
string path = GetPath(fileName);
string jsonString = JsonUtility.ToJson(data);
using StreamWriter writer = new StreamWriter(path);
writer.Write(jsonString);
}
public static T LoadData<T>(string fileName)
{
string path = GetPath(fileName);
using StreamReader reader = new StreamReader(path);
string json = reader.ReadToEnd();
return JsonUtility.FromJson<T>(json);
}
public static bool FileExists(string fileName)
{
string path = GetPath(fileName);
return File.Exists(path);
}
}
Then, I have this container class to store the data. As it is generic, I can pass any class to it:
public class JsonDataUser<T>
{
public T JsonData;
private string jsonFileName;
public void SaveData()
{
JsonDataManagement.SaveData<T>(jsonFileName, JsonData);
}
public JsonDataUser(T _StartJsonData, string _jsonFileName)
{
jsonFileName = _jsonFileName;
/// <summary>
/// Currently we only need to load the data once as the game begins
/// This is why we do the loading here in the constructor and why
/// we don't have a dedicated load method
/// </summary>
if (JsonDataManagement.FileExists(jsonFileName) == true)
{
JsonData = JsonDataManagement.LoadData<T>(jsonFileName);
}
else
{
JsonData = _StartJsonData;
}
}
}