generated from Common-Games/Template.UnityPackage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSavedValue.cs
84 lines (63 loc) · 1.97 KB
/
SavedValue.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
using System;
using JetBrains.Annotations;
namespace CGTK.Utils.Extensions.CGPlayerPrefs
{
using static PackageConstants;
/// <summary>
/// An abstract, simple implementation of <see cref="ISavedValue{T}"/>
/// </summary>
///
/// <typeparam name="T"> Type of the saved value. </typeparam>
[PublicAPI]
public abstract class SavedValue<T> : ISavedValue<T>
{
#region Fields & Properties
protected String Key { get; }
protected T DefaultValue { get; }
private Boolean _isCached;
private T _valueInternal;
public T Value
{
get
{
if (Key.IsNullOrEmpty()) throw new Exception(message: "Not initialized");
if (_isCached) return _valueInternal;
_valueInternal = IsSet ? Read() : DefaultValue;
_isCached = true;
return _valueInternal;
}
set
{
if (Key.IsNullOrEmpty()) throw new Exception(message: "Not initialized");
Write(value);
_valueInternal = value;
_isCached = true;
}
}
#endregion
#region Structors
public SavedValue(in String key, in T defaultValue = default)
{
Key = key;
DefaultValue = defaultValue;
}
#endregion
#region Methods
public void Delete()
{
UnityEngine.PlayerPrefs.DeleteKey(Key);
_valueInternal = DefaultValue;
}
public Boolean IsSet
{
get
{
if (Key.IsNullOrEmpty()) throw new Exception(message: "Not initialized");
return UnityEngine.PlayerPrefs.HasKey(Key);
}
}
public abstract T Read();
public abstract void Write(in T value);
#endregion
}
}