Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void Save<T>(T data, string path)
- {
- string jsonData = JsonUtility.ToJson(data);
- string hash = SaveUtils.ComputeHash(jsonData);
- SaveWrapper<T> wrapper = new SaveWrapper<T>
- {
- data = data,
- hash = hash
- };
- string finalJson = JsonUtility.ToJson(wrapper, true);
- string dir = Path.GetDirectoryName(path);
- if (!Directory.Exists(dir))
- Directory.CreateDirectory(dir);
- File.WriteAllText(path, finalJson);
- }
- public static T Load<T>(string path)
- {
- if (!File.Exists(path))
- return default;
- string json = File.ReadAllText(path);
- SaveWrapper<T> wrapper = JsonUtility.FromJson<SaveWrapper<T>>(json);
- if (wrapper == null || wrapper.data == null)
- return default;
- string jsonData = JsonUtility.ToJson(wrapper.data);
- string computedHash = SaveUtils.ComputeHash(jsonData);
- if (computedHash != wrapper.hash)
- {
- Debug.LogError("T'as modif' coquinou !!!");
- return default;
- }
- return wrapper.data;
- }
- [System.Serializable]
- public class SaveWrapper<T>
- {
- public T data;
- public string hash;
- }
- // Tu t'fais ton Utils
- public static class SaveUtils
- {
- public static string ComputeHash(string truc)
- {
- //Si t'es énervé
- const string SECRET_KEY = "PHOQUE_ME";
- using (var sha = SHA256.Create())
- {
- byte[] bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(truc + SECRET_KEY));
- return System.Convert.ToBase64String(bytes);
- }
- }
- }
Add Comment
Please, Sign In to add comment