Last change
on this file since 477 was 455, checked in by alloc, 16 months ago |
25_30_44
- Got rid (mostly) of custom JSON serialization
- Some code cleanup
|
File size:
1.6 KB
|
Rev | Line | |
---|
[142] | 1 | using System;
|
---|
| 2 | using System.IO;
|
---|
| 3 | using System.Runtime.Serialization;
|
---|
| 4 | using System.Runtime.Serialization.Formatters.Binary;
|
---|
| 5 |
|
---|
[325] | 6 | namespace AllocsFixes.PersistentData {
|
---|
[143] | 7 | [Serializable]
|
---|
[325] | 8 | public class PersistentContainer {
|
---|
[448] | 9 | private const string persistentDataFileName = "/AllocsPersistentData.bin";
|
---|
| 10 |
|
---|
[144] | 11 | private Players players;
|
---|
[325] | 12 | [OptionalField] private Attributes attributes;
|
---|
[144] | 13 |
|
---|
[455] | 14 | public Players Players => players ??= new Players ();
|
---|
[325] | 15 |
|
---|
[455] | 16 | public Attributes Attributes => attributes ??= new Attributes ();
|
---|
[144] | 17 |
|
---|
[142] | 18 | private static PersistentContainer instance;
|
---|
| 19 |
|
---|
[455] | 20 | public static PersistentContainer Instance => instance ??= new PersistentContainer ();
|
---|
[325] | 21 |
|
---|
| 22 | private PersistentContainer () {
|
---|
[142] | 23 | }
|
---|
[448] | 24 |
|
---|
[325] | 25 | public void Save () {
|
---|
[448] | 26 | lock (fileLockObject) {
|
---|
[455] | 27 | using Stream stream = File.Open ($"{GameIO.GetSaveGameDir ()}{persistentDataFileName}", FileMode.Create);
|
---|
[448] | 28 | BinaryFormatter bFormatter = new BinaryFormatter ();
|
---|
| 29 | bFormatter.Serialize (stream, this);
|
---|
| 30 | }
|
---|
[142] | 31 | }
|
---|
| 32 |
|
---|
[325] | 33 | public static bool Load () {
|
---|
[455] | 34 | var filePath = $"{GameIO.GetSaveGameDir ()}{persistentDataFileName}";
|
---|
| 35 |
|
---|
| 36 | if (!File.Exists (filePath)) {
|
---|
[326] | 37 | return false;
|
---|
[146] | 38 | }
|
---|
[325] | 39 |
|
---|
[326] | 40 | try {
|
---|
| 41 | PersistentContainer obj;
|
---|
[448] | 42 | lock (fileLockObject) {
|
---|
[455] | 43 | using Stream stream = File.Open (filePath, FileMode.Open);
|
---|
[448] | 44 | BinaryFormatter bFormatter = new BinaryFormatter ();
|
---|
| 45 | obj = (PersistentContainer)bFormatter.Deserialize (stream);
|
---|
| 46 | }
|
---|
| 47 |
|
---|
[326] | 48 | instance = obj;
|
---|
| 49 | return true;
|
---|
| 50 | } catch (Exception e) {
|
---|
| 51 | Log.Error ("Exception in PersistentContainer.Load");
|
---|
| 52 | Log.Exception (e);
|
---|
| 53 | }
|
---|
| 54 |
|
---|
[146] | 55 | return false;
|
---|
[142] | 56 | }
|
---|
[448] | 57 |
|
---|
| 58 | private static readonly object fileLockObject = new();
|
---|
[142] | 59 | }
|
---|
[325] | 60 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.