Repository navigation
Expand file tree
/
Copy pathXmlSaveLoadService.cs
More file actions
66 lines (59 loc) · 2.02 KB
/
Copy pathXmlSaveLoadService.cs
File metadata and controls
66 lines (59 loc) · 2.02 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
using System;
using System.IO;
using System.Xml.Serialization;
using Code.Services.PersistenceProgress;
using Code.Services.PersistenceProgress.Player;
using UnityEngine;
namespace Code.Services.SaveLoad
{
public class XmlSaveLoadService : ISaveLoadService
{
private const string FileName = "player_data.xml";
private readonly IPersistenceProgressService _progressService;
private readonly string _savePath;
public XmlSaveLoadService(IPersistenceProgressService progressService)
{
_progressService = progressService;
_savePath = Path.Combine(Application.persistentDataPath, FileName);
}
public void SaveProgress()
{
Save(_progressService.PlayerData);
}
public void Save(PlayerData playerData)
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
using FileStream stream = new FileStream(_savePath, FileMode.Create);
serializer.Serialize(stream, playerData);
Debug.Log($"XML Save complete at: {_savePath}");
}
catch (Exception e)
{
Debug.LogError($"Failed to save XML: {e.Message}");
}
}
public PlayerData Load()
{
try
{
if (!File.Exists(_savePath))
{
Debug.LogWarning("⚠XML save file not found.");
return null;
}
XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
using FileStream stream = new FileStream(_savePath, FileMode.Open);
var data = (PlayerData)serializer.Deserialize(stream);
Debug.Log("XML Load complete.");
return data;
}
catch (Exception e)
{
Debug.LogError($"Failed to load XML: {e.Message}");
return null;
}
}
}
}