|
1 |
| -using Sirenix.Serialization; |
| 1 | +using Sirenix.Serialization; |
2 | 2 | using System.Collections.Generic;
|
3 | 3 | using System.IO;
|
4 | 4 | using UnityEngine;
|
5 | 5 |
|
6 | 6 | namespace ToolBox.Serialization
|
7 | 7 | {
|
| 8 | + public class Item<T> : ISerializable |
| 9 | + { |
| 10 | + public T Value = default; |
| 11 | + } |
| 12 | + |
8 | 13 | public static class DataSerializer
|
9 | 14 | {
|
10 | 15 | private static Dictionary<string, ISerializable> _data = null;
|
11 | 16 | private static int _currentProfileIndex = 0;
|
12 | 17 |
|
13 | 18 | private const string FILE_NAME = "Save";
|
14 | 19 | private const DataFormat DATA_FORMAT = DataFormat.Binary;
|
| 20 | + private const int INITIAL_SIZE = 64; |
15 | 21 |
|
16 |
| - public static void Save<T>(string saveKey, T dataToSave) where T : ISerializable |
| 22 | + public static void Save<T>(string key, T dataToSave) |
17 | 23 | {
|
18 |
| - if (_data.ContainsKey(saveKey)) |
19 |
| - _data[saveKey] = dataToSave; |
| 24 | + if (_data.TryGetValue(key, out var data)) |
| 25 | + { |
| 26 | + var item = (Item<T>)data; |
| 27 | + item.Value = dataToSave; |
| 28 | + } |
20 | 29 | else
|
21 |
| - _data.Add(saveKey, dataToSave); |
| 30 | + { |
| 31 | + var saveItem = new Item<T> { Value = dataToSave }; |
| 32 | + _data.Add(key, saveItem); |
| 33 | + } |
22 | 34 | }
|
23 | 35 |
|
24 |
| - public static bool TryLoad<T>(string loadKey, out T data) where T : ISerializable |
| 36 | + public static T Load<T>(string key) |
25 | 37 | {
|
26 |
| - var hasData = _data.TryGetValue(loadKey, out var value); |
27 |
| - data = value != null ? (T)value : default; |
| 38 | + _data.TryGetValue(key, out var value); |
| 39 | + var loadItem = (Item<T>)value; |
28 | 40 |
|
29 |
| - return hasData; |
| 41 | + return loadItem.Value; |
30 | 42 | }
|
31 | 43 |
|
| 44 | + public static bool HasKey(string key) => |
| 45 | + _data.ContainsKey(key); |
| 46 | + |
| 47 | + public static void DeleteKey(string key) => |
| 48 | + _data.Remove(key); |
| 49 | + |
| 50 | + public static void DeleteAll() => |
| 51 | + _data.Clear(); |
| 52 | + |
32 | 53 | public static void ChangeProfile(int profileIndex)
|
33 | 54 | {
|
34 | 55 | if (_currentProfileIndex == profileIndex)
|
@@ -72,7 +93,7 @@ private static void LoadFile()
|
72 | 93 | _data = SerializationUtility.DeserializeValue<Dictionary<string, ISerializable>>(loadBytes, DATA_FORMAT);
|
73 | 94 |
|
74 | 95 | if (_data == null)
|
75 |
| - _data = new Dictionary<string, ISerializable>(10); |
| 96 | + _data = new Dictionary<string, ISerializable>(INITIAL_SIZE); |
76 | 97 | }
|
77 | 98 |
|
78 | 99 | private static string GetFilePath(int profileIndex) =>
|
|
0 commit comments