在Unity中保存/加载数据

Joe*_*eyL 6 c# serialization unity-game-engine

我一直在使用Unity中的保存和加载,我将序列化的类保存到文件中.我有一个Serializable类:

[Serializable]
class Save
{
    public List<int> ID = new List<int>();
    public List<int> Amounts = new List<int>();
}
Run Code Online (Sandbox Code Playgroud)

并将其保存到文件A-OK.我可以加载它没有错误,但如果我想稍后添加:

[Serializable]
class Save
{
    public List<int> ID = new List<int>();
    public List<int> Amounts = new List<int>();
    public int extra = 0;
}
Run Code Online (Sandbox Code Playgroud)

我运行我的脚本它给了我一个反序列化错误,我完全理解,当我将反序列化文件转换为我的新类'保存'时,我添加的新变量不存在,它给了我错误.

我在商店中修复资产时发现了这个错误,我知道一个修复可以只是更改文件名,因此创建了一个新文件,但我不想只删除之前保存的内容.

所以我的问题是,如果我想在我的序列化类中添加更多变量,如果人们要更新资产,我将如何捕获并调整旧版本的变量?

谢谢!

Pro*_*mer 19

使用C#serializer时会出现此问题.将数据转换为Json,JsonUtility然后将其保存PlayerPrefs.加载时,加载PlayerPrefs然后将json转换回类JsonUtility.

保存示例类:

[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;
}
Run Code Online (Sandbox Code Playgroud)

保存数据:

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();
}
Run Code Online (Sandbox Code Playgroud)

加载数据:

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]);
    }
}
Run Code Online (Sandbox Code Playgroud)

JsonUtility.FromJson和之间的区别JsonUtility.FromJsonOverwrite:

.JsonUtility.FromJson从Json创建新的Object并返回它.它分配内存.

string jsonData = PlayerPrefs.GetString("MySettings");
//Convert to Class. FromJson creates new Save instance
Save loadedData = JsonUtility.FromJson<Save>(jsonData);
Run Code Online (Sandbox Code Playgroud)

.JsonUtility.FromJsonOverwrite没有创建新的对象.它与为您的类添加更多数据类型无关.它只是覆盖在其中传递的数据.它有利于记忆保存和减少GC.唯一的一次,如果当你拥有领域,因为它会分配内存array,stringList.

JsonUtility.FromJsonOverwrite应该使用的示例是使用Json执行常量数据传输.它将提高性能.

//Create Save instance **once** in the Start or Awake function
Save loadedData = null;
void Start()
{
    //loadedData instance is created once
    loadedData = new Save();
}

void Load()
{
    string jsonData = PlayerPrefs.GetString("MySettings");
    //Convert to Class but don't create new Save Object. Re-use loadedData and overwrite old data in it
    JsonUtility.FromJsonOverwrite(jsonData, loadedData);
    Debug.Log("High Score: " + loadedData.highScore);
}
Run Code Online (Sandbox Code Playgroud)