In Unity, when saving data as a serialized class, adding additional variables to the class can cause conflicts when loading older versions of the saved file. To handle this gracefully, consider converting the data to JSON format.
Use JsonUtility.ToJson to convert the serialized class to a JSON string. Save this string using PlayerPrefs.SetString or other preferred methods. When loading the data, use JsonUtility.FromJson to convert the JSON string back into the class.
Save Data:
using UnityEngine; using System; using System.Collections.Generic; [Serializable] public class Save { public List<int> ID = new List<int>(); public List<int> Amounts = new List<int>(); public int extra = 0; public float highScore = 0; public string ToJson() { return JsonUtility.ToJson(this); } public static Save FromJson(string json) { return JsonUtility.FromJson<Save>(json); } } void Save() { Save saveData = new Save(); ... // Populate the data fields string jsonData = saveData.ToJson(); PlayerPrefs.SetString("MySettings", jsonData); PlayerPrefs.Save(); }
Load Data:
void Load() { string jsonData = PlayerPrefs.GetString("MySettings"); Save loadedData = Save.FromJson(jsonData); ... // Use the loaded data }
The above is the detailed content of How Can I Safely Save and Load Data in Unity, Handling Changes to My Serializable Class?. For more information, please follow other related articles on the PHP Chinese website!