-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDataManager.cs
67 lines (59 loc) · 1.77 KB
/
DataManager.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
using UnityEngine;
using System;
public class DataManager : MonoBehaviour
{
public static DataManager Instance { get; private set; }
private void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
public void SaveData(string key, object value)
{
if (value is int intValue)
PlayerPrefs.SetInt(key, intValue);
else if (value is float floatValue)
PlayerPrefs.SetFloat(key, floatValue);
else if (value is string stringValue)
PlayerPrefs.SetString(key, stringValue);
else
Debug.LogError($"Unsupported data type for saving: {value.GetType()}");
PlayerPrefs.Save();
}
public T LoadData<T>(string key, T defaultValue)
{
if (!PlayerPrefs.HasKey(key))
return defaultValue;
if (typeof(T) == typeof(int))
return (T)Convert.ChangeType(PlayerPrefs.GetInt(key), typeof(T));
else if (typeof(T) == typeof(float))
return (T)Convert.ChangeType(PlayerPrefs.GetFloat(key), typeof(T));
else if (typeof(T) == typeof(string))
return (T)Convert.ChangeType(PlayerPrefs.GetString(key), typeof(T));
else
{
Debug.LogError($"Unsupported data type for loading: {typeof(T)}");
return defaultValue;
}
}
public void DeleteData(string key)
{
if (PlayerPrefs.HasKey(key))
{
PlayerPrefs.DeleteKey(key);
PlayerPrefs.Save();
}
}
public void DeleteAllData()
{
PlayerPrefs.DeleteAll();
PlayerPrefs.Save();
}
}