Handling Serialization Changes with Unity's Save/Load System
Despite the convenience of Unity's serialization, it poses a challenge when adding variables to serialized classes. This issue manifests as deserialization errors when loading an older version of a serialized file, as the new variable doesn't exist.
Utilizing JSON as an Intermediate Format
To address this problem, we can leverage JSON (JavaScript Object Notation) as an intermediate data format. By converting the serialized class to JSON before saving and back to an object on loading, we can avoid deserialization errors caused by missing variables.
Example Class Structure
[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; }
Saving Data with JSON
void Save() { Save saveData = new Save(); saveData.extra = 99; saveData.highScore = 40; // Convert to JSON string jsonData = JsonUtility.ToJson(saveData); // Save JSON string PlayerPrefs.SetString("MySettings", jsonData); PlayerPrefs.Save(); }
Loading Data with JSON
void Load() { // Load saved JSON string jsonData = PlayerPrefs.GetString("MySettings"); // Convert to Class Save loadedData = JsonUtility.FromJson<Save>(jsonData); // Display saved data Debug.Log("Extra: " + loadedData.extra); Debug.Log("High Score: " + loadedData.highScore); for (int i = 0; i < loadedData.ID.Count; i++) { Debug.Log("ID: " + loadedData.ID[i]); } for (int i = 0; i < loadedData.Amounts.Count; i++) { Debug.Log("Amounts: " + loadedData.Amounts[i]); } }
Difference between JsonUtility.FromJson and JsonUtility.FromJsonOverwrite
The above is the detailed content of How Can I Handle Serialization Changes in Unity's Save/Load System Using JSON?. For more information, please follow other related articles on the PHP Chinese website!