Skip to content

Instantly share code, notes, and snippets.

@GarethIW
Last active December 19, 2023 19:23
Show Gist options
  • Save GarethIW/72c82d2fae8dc60d3fc15f49eff30516 to your computer and use it in GitHub Desktop.
Save GarethIW/72c82d2fae8dc60d3fc15f49eff30516 to your computer and use it in GitHub Desktop.
Simple SO/Json data stuff
public class PlayerData
{
public string Name;
public Vector3 Position;
public int Coins;
}
using System;
using System.IO;
using Newtonsoft.Json;
using UnityEngine;
public class PlayerDataObject : ScriptableObject
{
public PlayerData PlayerData => _playerData;
private PlayerData _playerData = new PlayerData();
[Tooltip("Automatically save data on app exit")]
[SerializeField] private bool _autoSave = true;
private void OnEnable()
{
Load();
}
private void OnDestroy()
{
if(_autoSave)
Save();
}
public override void Load()
{
try
{
string fn = Path.Combine(Application.persistentDataPath, "Save", _playerData.GetType().Name + ".json");
if (File.Exists(fn))
{
string json = File.ReadAllText(fn);
// Add decryption here
_playerData = JsonConvert.DeserializeObject<T>(json);
}
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
public override void Save()
{
try
{
string fn = Path.Combine(Application.persistentDataPath, "Save", _playerData.GetType().Name + ".json");
if (!Directory.Exists(Path.GetDirectoryName(fn)))
Directory.CreateDirectory(Path.GetDirectoryName(fn));
string json = JsonConvert.SerializeObject(_playerData, Formatting.Indented);
// Encrypt the json string here
File.WriteAllText(fn, json);
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment