Skip to content

Commit c3f1371

Browse files
authored
Update DataSerializer.cs
1 parent d6ed5cd commit c3f1371

File tree

1 file changed

+31
-10
lines changed

1 file changed

+31
-10
lines changed

DataSerializer.cs

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,55 @@
1-
using Sirenix.Serialization;
1+
using Sirenix.Serialization;
22
using System.Collections.Generic;
33
using System.IO;
44
using UnityEngine;
55

66
namespace ToolBox.Serialization
77
{
8+
public class Item<T> : ISerializable
9+
{
10+
public T Value = default;
11+
}
12+
813
public static class DataSerializer
914
{
1015
private static Dictionary<string, ISerializable> _data = null;
1116
private static int _currentProfileIndex = 0;
1217

1318
private const string FILE_NAME = "Save";
1419
private const DataFormat DATA_FORMAT = DataFormat.Binary;
20+
private const int INITIAL_SIZE = 64;
1521

16-
public static void Save<T>(string saveKey, T dataToSave) where T : ISerializable
22+
public static void Save<T>(string key, T dataToSave)
1723
{
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+
}
2029
else
21-
_data.Add(saveKey, dataToSave);
30+
{
31+
var saveItem = new Item<T> { Value = dataToSave };
32+
_data.Add(key, saveItem);
33+
}
2234
}
2335

24-
public static bool TryLoad<T>(string loadKey, out T data) where T : ISerializable
36+
public static T Load<T>(string key)
2537
{
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;
2840

29-
return hasData;
41+
return loadItem.Value;
3042
}
3143

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+
3253
public static void ChangeProfile(int profileIndex)
3354
{
3455
if (_currentProfileIndex == profileIndex)
@@ -72,7 +93,7 @@ private static void LoadFile()
7293
_data = SerializationUtility.DeserializeValue<Dictionary<string, ISerializable>>(loadBytes, DATA_FORMAT);
7394

7495
if (_data == null)
75-
_data = new Dictionary<string, ISerializable>(10);
96+
_data = new Dictionary<string, ISerializable>(INITIAL_SIZE);
7697
}
7798

7899
private static string GetFilePath(int profileIndex) =>

0 commit comments

Comments
 (0)