using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using System; public static class PlayerPrefsUtil { public static bool GetBool(string key, bool defaultValue) { if (!PlayerPrefs.HasKey(key)) { return defaultValue; } return GetBool(key); } public static bool GetBool(string key) { return PlayerPrefs.GetInt(key) != 0; } public static void SetBool(string key, bool value) { PlayerPrefs.SetInt(key, value ? 1 : 0); } public static T GetObject(string key, T defaultValue) { if (!PlayerPrefs.HasKey(key)) { return defaultValue; } return GetObject(key); } public static T GetObject(string key) { string json = PlayerPrefs.GetString(key, "{}"); return JsonUtility.FromJson(json); } public static void SetObject(string key, T value) { string json = JsonUtility.ToJson(value); PlayerPrefs.SetString(key, json); } /// /// save list /// public static void SaveList(string key, List value) { string serizlizedList = Serialize>(value); PlayerPrefs.SetString(key, serizlizedList); } /// /// load list /// public static List LoadList(string key) { //Read only when there is a key if (PlayerPrefs.HasKey(key)) { string serizlizedList = PlayerPrefs.GetString(key); return Deserialize>(serizlizedList); } return new List(); } //================================================================================= //Serialize, Deserialize //================================================================================= private static string Serialize(T obj) { BinaryFormatter binaryFormatter = new BinaryFormatter(); MemoryStream memoryStream = new MemoryStream(); binaryFormatter.Serialize(memoryStream, obj); return Convert.ToBase64String(memoryStream.GetBuffer()); } private static T Deserialize(string str) { BinaryFormatter binaryFormatter = new BinaryFormatter(); MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(str)); return (T)binaryFormatter.Deserialize(memoryStream); } }