
Saving Data in Unity: Handling Changes in the Serializable Class
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.
Convert to JSON for Save/Load Flexibility
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.
Example Code for Data Conversion
Save Data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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();
...
string jsonData = saveData.ToJson();
PlayerPrefs.SetString( "MySettings" , jsonData);
PlayerPrefs.Save();
}
|
Copy after login
Load Data:
1 2 3 4 5 6 7 | void Load()
{
string jsonData = PlayerPrefs.GetString( "MySettings" );
Save loadedData = Save.FromJson(jsonData);
...
}
|
Copy after login
Additional Considerations
-
JsonUtility.FromJsonOverwrite: This method allows overwriting existing data in an instance without creating a new instance. This can be useful for updating data structures like arrays or lists.
-
Memory Allocation: Converting to JSON can involve memory allocation for lists and strings. Consider reusing existing instances where possible.
-
Data Compatibility: Ensure that when making changes to the class, older versions of the data can still be loaded by providing fallback values or handling missing variables gracefully.
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!