PlayerPrefsUtil.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.Runtime.Serialization.Formatters.Binary;
  5. using System.IO;
  6. using System;
  7. public static class PlayerPrefsUtil
  8. {
  9. public static bool GetBool(string key, bool defaultValue)
  10. {
  11. if (!PlayerPrefs.HasKey(key))
  12. {
  13. return defaultValue;
  14. }
  15. return GetBool(key);
  16. }
  17. public static bool GetBool(string key)
  18. {
  19. return PlayerPrefs.GetInt(key) != 0;
  20. }
  21. public static void SetBool(string key, bool value)
  22. {
  23. PlayerPrefs.SetInt(key, value ? 1 : 0);
  24. }
  25. public static T GetObject<T>(string key, T defaultValue)
  26. {
  27. if (!PlayerPrefs.HasKey(key))
  28. {
  29. return defaultValue;
  30. }
  31. return GetObject<T>(key);
  32. }
  33. public static T GetObject<T>(string key)
  34. {
  35. string json = PlayerPrefs.GetString(key, "{}");
  36. return JsonUtility.FromJson<T>(json);
  37. }
  38. public static void SetObject<T>(string key, T value)
  39. {
  40. string json = JsonUtility.ToJson(value);
  41. PlayerPrefs.SetString(key, json);
  42. }
  43. /// <summary>
  44. /// save list
  45. /// </summary>
  46. public static void SaveList<T>(string key, List<T> value)
  47. {
  48. string serizlizedList = Serialize<List<T>>(value);
  49. PlayerPrefs.SetString(key, serizlizedList);
  50. }
  51. /// <summary>
  52. /// load list
  53. /// </summary>
  54. public static List<T> LoadList<T>(string key)
  55. {
  56. //Read only when there is a key
  57. if (PlayerPrefs.HasKey(key))
  58. {
  59. string serizlizedList = PlayerPrefs.GetString(key);
  60. return Deserialize<List<T>>(serizlizedList);
  61. }
  62. return new List<T>();
  63. }
  64. //=================================================================================
  65. //Serialize, Deserialize
  66. //=================================================================================
  67. private static string Serialize<T>(T obj)
  68. {
  69. BinaryFormatter binaryFormatter = new BinaryFormatter();
  70. MemoryStream memoryStream = new MemoryStream();
  71. binaryFormatter.Serialize(memoryStream, obj);
  72. return Convert.ToBase64String(memoryStream.GetBuffer());
  73. }
  74. private static T Deserialize<T>(string str)
  75. {
  76. BinaryFormatter binaryFormatter = new BinaryFormatter();
  77. MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(str));
  78. return (T)binaryFormatter.Deserialize(memoryStream);
  79. }
  80. }