// 设定的Data类,用于封装多种类型的数据 [System.Serializable] class SaveData { public string playerName; public int playerLevel; public int playerCoin; public Vector3 playerPosition; }
public static void SaveByPlayerPrefs(string key, object data) // 存储数据,先转成JSON格式再以String格式存储。 { var json = JsonUtility.ToJson(data); PlayerPrefs.SetString(key, json); PlayerPrefs.Save(); #if UNITY_EDITOR Debug.Log("Successfully saved data to PlayerPrefs."); #endif } public static string LoadByPlayerPrefs(string key) // 从注册表中读取数据 { return PlayerPrefs.GetString(key, null); }
public static void SaveByJSON(string saveFileName, object dataObject) { var json = JsonUtility.ToJson(dataObject); var path = Path.Combine(Application.persistentDataPath, saveFileName); try { File.WriteAllText(path,json); #if UNITY_EDITOR Debug.Log($"Successfully saved data to {path}"); #endif } catch (System.Exception e) { #if UNITY_EDITOR Debug.LogError($"Failed to save data to {path}. \n because of Exception : {e}"); #endif } } public static T LoadFromJSON<T>(string saveFileName) { var path = Path.Combine(Application.persistentDataPath, saveFileName); try { var json = File.ReadAllText(path); var data = JsonUtility.FromJson<T>(json); return data; } catch (System.Exception e) { #if UNITY_EDITOR Debug.LogError($"Failed to load data from {path}. \n because of Exception : {e}"); #endif return default; } } #region Deleting public static void DeleteSaveFile(string saveFileName) { var path = Path.Combine(Application.persistentDataPath, saveFileName); try { File.Delete(path); } catch (System.Exception e) { #if UNITY_EDITOR Debug.LogError($"Failed to delete data from {path}. \n because of Exception : {e}"); #endif } }