-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileDataHandler.cs
86 lines (72 loc) · 2.3 KB
/
FileDataHandler.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
/*
* Bridge between json file that is saved in default Unity dir, and CircleData
*
* Load() returns latest saved version of CircleData
* Save() updates json file with new CircleData
*/
public class FileDataHandler
{
private string dirPath = "";
private string dataFileName = "";
public FileDataHandler(string dirPath, string dataFileName)
{
this.dirPath = dirPath;
this.dataFileName = dataFileName;
}
public CircleData Load()
{
//use Path.Combine to account for dif separators for dif OS
string fullPath = Path.Combine(dirPath, dataFileName);
CircleData loadedData = null;
if (File.Exists(fullPath))
{
try
{
string dataToLoad = "";
using (FileStream stream = new FileStream(fullPath, FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
dataToLoad = reader.ReadToEnd();
}
}
//deserialize into CircleData
loadedData = JsonUtility.FromJson<CircleData>(dataToLoad);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
return loadedData;
}
public void Save(CircleData data)
{
string fullPath = Path.Combine(dirPath, dataFileName);
try
{
//create directory, if it doesnt already exist
Directory.CreateDirectory(dirPath);
//serialize circle data into json text
string dataToStore = JsonUtility.ToJson(data, true);
//update file with new serialized data
//when reading/ writing, use USING blocks, as it ensures streams are closed after use
using (FileStream stream = new FileStream(fullPath, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(dataToStore);
}
}
}
catch (Exception e)
{
Debug.LogException(e);
}
}
}