-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSaveFileService.cs
More file actions
116 lines (95 loc) · 3.4 KB
/
Copy pathSaveFileService.cs
File metadata and controls
116 lines (95 loc) · 3.4 KB
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
109
110
111
112
113
114
115
116
using System;
using System.IO;
using System.Text;
using UnityEngine;
namespace UnityRPG.Infrastructure.Save
{
public sealed class SaveFileService
{
private const string DefaultFileName = "save_0.json";
private readonly string filePath;
public string FilePath => filePath;
public SaveFileService(string fileName = DefaultFileName)
{
filePath = Path.Combine(Application.persistentDataPath, fileName);
}
public SaveLoadStatus Save(SaveGameData data)
{
if (data == null)
return SaveLoadStatus.InvalidData;
try
{
data.version = SaveGameData.CurrentVersion;
data.savedAtUtc = DateTime.UtcNow.ToString("O");
string json = JsonUtility.ToJson(data, true);
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
File.WriteAllText(filePath, json, Encoding.UTF8);
return SaveLoadStatus.Success;
}
catch (Exception exception)
{
Debug.LogError($"[Save] 파일 저장 실패: {exception.Message}");
return SaveLoadStatus.IoError;
}
}
public SaveLoadStatus Load(out SaveGameData data)
{
data = null;
if (!File.Exists(filePath))
return SaveLoadStatus.FileNotFound;
try
{
string json = File.ReadAllText(filePath, Encoding.UTF8);
if (string.IsNullOrWhiteSpace(json))
return SaveLoadStatus.InvalidData;
SaveGameData loadedData = JsonUtility.FromJson<SaveGameData>(json);
if (loadedData == null)
return SaveLoadStatus.InvalidData;
if (loadedData.version != SaveGameData.CurrentVersion)
return SaveLoadStatus.UnsupportedVersion;
if (!HasRequiredData(loadedData))
return SaveLoadStatus.InvalidData;
data = loadedData;
return SaveLoadStatus.Success;
}
catch (ArgumentException exception)
{
Debug.LogWarning($"[Save] JSON 데이터가 손상되었습니다: {exception.Message}");
return SaveLoadStatus.InvalidData;
}
catch (Exception exception)
{
Debug.LogError($"[Save] 파일 불러오기 실패: {exception.Message}");
return SaveLoadStatus.IoError;
}
}
public bool Exists()
{
return File.Exists(filePath);
}
public bool Delete()
{
if (!File.Exists(filePath))
return false;
try
{
File.Delete(filePath);
return true;
}
catch (Exception exception)
{
Debug.LogError($"[Save] 파일 삭제 실패: {exception.Message}");
return false;
}
}
private static bool HasRequiredData(SaveGameData data)
{
return data.player != null &&
data.inventory != null &&
data.equipment != null &&
data.quests != null &&
data.encounters != null &&
data.checkpoint != null;
}
}
}