【发布时间】:2015-05-26 21:50:24
【问题描述】:
我最近开始使用 Unity。目前,我在数据持久性方面陷入困境。虽然我可以创建一个文件,但它不包含序列化变量。我已经阅读并看过各种教程。不幸的是,我仍然没有领先。如果有人可以帮助我,我将不胜感激。
这是我的 SaveLoad.cs,我无需进行太多编辑即可使用:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public static class SaveLoad {
public static List<Game> savedGames = new List<Game>();
public static void Save() {
savedGames.Add(Game.current);
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create (Application.persistentDataPath + "/savedGames.gd");
bf.Serialize(file, SaveLoad.savedGames);
file.Close();
}
public static void Load() {
if(File.Exists(Application.persistentDataPath + "/savedGames.gd")) {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/savedGames.gd", FileMode.Open);
SaveLoad.savedGames = (List<Game>)bf.Deserialize(file);
file.Close();
}
}
}
这是我的 game.cs 与(我希望)我尝试保存的序列化变量:
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Game {
public static Game current;
public Click CurrentEuros { get; set; }
public Game () {
//CurrentEuros = 1;
CurrentEuros = new Click();
}
}
结果总是在 savedGames.gd “游戏”的最后一行。
【问题讨论】:
-
首先,感谢您的链接。但是,当我只需要在任何地方擦除“静态”时,就会出现一些错误“访问非静态成员‘SaveLoad.Save()’需要对象引用”。我猜这是因为“文件”类已经是静态的。
-
您也可以使用
XMLSerializer,而不是BinaryFormatter。这样你就可以阅读存档了。当您查看保存的内容并创建自定义保存游戏时,这使调试变得更加容易。
标签: c# unity3d persistence saving-data