在Unity上保存/加载游戏

时间:2017-10-30 11:54:15

标签: c# unity3d

在我的Unity游戏中,我有保存/加载机制。我在这里如何保存游戏:

// class with the all data, which need to be saved
[Serializable]
public class Saves : ScriptableObject
{
    public string dateTime;
    public int latestSaveSlot;
    public int actNumber;
    public string sceneName;
    public int currentActiveSlot;
}

// method in another class, which save data
public void ButtonSave()
{
    latestSaveSlot = currentActiveSlot;

    saves.dateTime = System.DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
    saves.latestSaveSlot = latestSaveSlot;
    saves.actNumber = gameManagerScript.currentActNumber;
    saves.sceneName = SceneManager.GetActiveScene().name;

    var serializedSave = JsonUtility.ToJson(saves);
    var saveFileName = Application.persistentDataPath + "/Save_" + currentActiveSlot + ".save";
    File.WriteAllText(saveFileName, serializedSave);
}

现在我需要加载它。我有6个保存位置。我需要这样的东西:

currentActNumber = saves.actNumber + currentActiveSlot;

..从我需要的插槽加载数据,但没有编辑变量的值。

6个保存位置 enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

根据您的意思,您的加载方法应如下所示:

public void LoadGame(int slot)
{
    string saveFileName = Application.persistentDataPath + "/Save_" + slot+ ".save";
    string saveFilecontent = File.ReadAllText(saveFileName);
    //please note, i have no idea if this works, because i don't know whay your
    //JsonUtility does. this is an educated guess.
    string deSerializedSave =  JsonUtility.FromJson<Saves>(saveFilecontent);

    saves = deSerializedSave;

    //you can now switch scene, set variables etc. form your "saves" object.

}