-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonSaveLoadService.cs
108 lines (94 loc) · 3.25 KB
/
JsonSaveLoadService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// Resharper disable all
// **************************************************************** //
//
// Copyright (c) RimuruDev. All rights reserved.
// Contact me:
// - Gmail: rimuru.dev@gmail.com
// - GitHub: https://github.com/RimuruDev
// - LinkedIn: https://www.linkedin.com/in/rimuru/
// - GitHub Organizations: https://github.com/Rimuru-Dev
//
// **************************************************************** //
using System;
using System.IO;
using UnityEngine;
using Newtonsoft.Json;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace RimuruDev.StorageService
{
[HelpURL("https://github.com/RimuruDev/Unity-JsonSaveLoadService")]
public sealed class JsonSaveLoadService : ISaveLoadService
{
private const string FileFormat = ".json";
private static string _customPathInEditor = "Assets/Saves";
public void Save<TData>(TData data, string key)
{
if (string.IsNullOrWhiteSpace(key))
{
Debug.LogError("Save operation failed: Key is null or whitespace.");
return;
}
if (data == null)
{
Debug.LogError("Save operation failed: Data is null.");
return;
}
try
{
var filePath = GetFilePath(key);
var directoryPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath ??
throw new InvalidOperationException("Directory path is null."));
}
var jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
File.WriteAllText(filePath, jsonData);
}
catch (Exception ex)
{
Debug.LogError($"Error when saving data: {ex.Message}");
}
}
public TData Load<TData>(string key, TData defaultValue = default)
{
if (string.IsNullOrWhiteSpace(key))
{
Debug.LogError("Load operation failed: Key is null or whitespace.");
return defaultValue;
}
try
{
var filePath = GetFilePath(key);
if (File.Exists(filePath))
{
var jsonData = File.ReadAllText(filePath);
return JsonConvert.DeserializeObject<TData>(jsonData);
}
}
catch (Exception ex)
{
Debug.LogError($"Error when loading data: {ex.Message}");
}
return defaultValue;
}
private static string GetFilePath(string key)
{
#if UNITY_EDITOR
return Path.Combine(_customPathInEditor, $"{key}{FileFormat}");
#else
return Path.Combine(Application.persistentDataPath, $"{key}{FileFormat}");
#endif
}
#if UNITY_EDITOR
public void SetCustomPathInEditor(string customPath)
{
_customPathInEditor = customPath;
if (!Directory.Exists(_customPathInEditor))
Directory.CreateDirectory(_customPathInEditor);
}
#endif
}
}