我尝试几天来学习如何将数据保留在游戏中
我想保留一个数字以供学习,但我不明白为什么我不能这样做
[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);
}
}
答案 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);
}