Last active
December 19, 2023 19:23
-
-
Save GarethIW/72c82d2fae8dc60d3fc15f49eff30516 to your computer and use it in GitHub Desktop.
Simple SO/Json data stuff
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PlayerData | |
{ | |
public string Name; | |
public Vector3 Position; | |
public int Coins; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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