using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace AllocsFixes.PersistentData { [Serializable] public class PersistentContainer { private const string persistentDataFileName = "/AllocsPersistentData.bin"; private Players players; [OptionalField] private Attributes attributes; public Players Players => players ??= new Players (); public Attributes Attributes => attributes ??= new Attributes (); private static PersistentContainer instance; public static PersistentContainer Instance => instance ??= new PersistentContainer (); private PersistentContainer () { } public void Save () { lock (fileLockObject) { using Stream stream = File.Open ($"{GameIO.GetSaveGameDir ()}{persistentDataFileName}", FileMode.Create); BinaryFormatter bFormatter = new BinaryFormatter (); bFormatter.Serialize (stream, this); } } public static bool Load () { var filePath = $"{GameIO.GetSaveGameDir ()}{persistentDataFileName}"; if (!File.Exists (filePath)) { return false; } try { PersistentContainer obj; lock (fileLockObject) { using Stream stream = File.Open (filePath, FileMode.Open); BinaryFormatter bFormatter = new BinaryFormatter (); obj = (PersistentContainer)bFormatter.Deserialize (stream); } instance = obj; return true; } catch (Exception e) { Log.Error ("Exception in PersistentContainer.Load"); Log.Exception (e); } return false; } private static readonly object fileLockObject = new(); } }