无法保存游戏

时间:2019-07-19 08:59:53

标签: c# unity3d save

我尝试几天来学习如何将数据保留在游戏中

我想保留一个数字以供学习,但我不明白为什么我不能这样做

[System.Serializable]
public class Save 
{
    public int Cuens;
    void Update () 
    {
        if (Input.GetKey (KeyCode.T)) {
            Cuens += 5;
            SaveGame ();
        }
        if (Input.GetKey (KeyCode.Y))
            LodeGame ();
    }
    void SaveGame()
    {
        BinaryFormatter bf = new BinaryFormatter ();
        FileStream file = File.Create (Application.persistentDataPath + "/gamesave.save");
        Game save = new Game (Cuens);
        bf.Serialize (file, save);
        file.Close ();
        Debug.Log (save);
    }
    void LodeGame()
    {
        BinaryFormatter bf = new BinaryFormatter ();
        FileStream file = File.Open (Application.persistentDataPath + "/gamesave.save", FileMode.Open);
        Game save = (Game)bf.Deserialize (file);
        file.Close ();
        Debug.Log (save);
    }
}

1 个答案:

答案 0 :(得分:0)

从文件加载游戏状态时,会创建一个新的Game对象,但永远不会对其进行任何操作:

 void LodeGame()
{
    BinaryFormatter bf = new BinaryFormatter ();
    FileStream file = File.Open (Application.persistentDataPath + "/gamesave.save", FileMode.Open);
    Game save = (Game)bf.Deserialize (file);
    // you never do something with this
    file.Close ();
    Debug.Log (save);
}

一种简单的方法是将加载的数据写回到当前的Game对象中:

 void LodeGame()
{
    BinaryFormatter bf = new BinaryFormatter ();
    FileStream file = File.Open (Application.persistentDataPath + "/gamesave.save", FileMode.Open);
    Game save = (Game)bf.Deserialize (file);
    file.Close ();
    this.Cuens = save.Cuens; // restore value.
    Debug.Log (save);
}