Home >Backend Development >C++ >How Can I Handle Serialization Changes in Unity's Save/Load System Using JSON?

How Can I Handle Serialization Changes in Unity's Save/Load System Using JSON?

DDD
DDDOriginal
2025-01-04 22:50:41716browse

How Can I Handle Serialization Changes in Unity's Save/Load System Using JSON?

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

  • JsonUtility.FromJson: Creates a new object from JSON and returns it, allocating memory.
  • JsonUtility.FromJsonOverwrite: Overwrites the passed-in object with JSON data, not creating any new objects. This can save memory and reduce GC usage when performing frequent data transfer with JSON.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn