Repository navigation
Expand file tree
/
Copy pathJsonSaveLoadService.cs
More file actions
58 lines (50 loc) · 1.65 KB
/
Copy pathJsonSaveLoadService.cs
File metadata and controls
58 lines (50 loc) · 1.65 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
using System;
using System.IO;
using Code.Services.PersistenceProgress;
using Code.Services.PersistenceProgress.Player;
using UnityEngine;
namespace Code.Services.SaveLoad
{
public class JsonSaveLoadService : ISaveLoadService
{
private const string FileName = "player_data.json";
private readonly IPersistenceProgressService _progressService;
private string FilePath => Path.Combine(Application.persistentDataPath, FileName);
public JsonSaveLoadService(IPersistenceProgressService progressService)
{
_progressService = progressService;
}
public void SaveProgress() => Save(_progressService.PlayerData);
public void Save(PlayerData playerData)
{
try
{
string data = JsonUtility.ToJson(playerData, true);
File.WriteAllText(FilePath, data);
Debug.Log($"JSON Save complete at: {FilePath}");
}
catch (Exception e)
{
Debug.LogError($"Failed to save JSON: {e.Message}");
}
}
public PlayerData Load()
{
try
{
if (!File.Exists(FilePath))
{
Debug.LogWarning($"JSON file not found at: {FilePath}");
return null;
}
string data = File.ReadAllText(FilePath);
return JsonUtility.FromJson<PlayerData>(data);
}
catch (Exception e)
{
Debug.LogError($"Failed to load JSON: {e.Message}");
return null;
}
}
}
}