问题
我的问题是,当我将游戏构建为.apk时,我无法在Android上序列化和反序列化列表。代码在Unity编辑器中工作正常。我无法收到任何错误消息,因为问题只会在我构建游戏时出现。
设置文件路径
private void Start () {
if (Application.platform == RuntimePlatform.Android) {
// Android
string oriPath = Path.Combine (Application.streamingAssetsPath, "Data.xml");
// Android only use WWW to read file
WWW reader = new WWW (oriPath);
while (!reader.isDone) { }
string realPath = Application.persistentDataPath + "/Data";
File.WriteAllBytes (realPath, reader.bytes);
dbPath = realPath;
} else {
// iOS and Unity Editor
dbPath = Path.Combine (Application.streamingAssetsPath, "Data.xml");
}
}
从文件加载
public void LoadItems () {
FileStream stream;
if (!File.Exists(dbPath)) {
stream = new FileStream (dbPath, FileMode.Create);
stream.Close ();
stream.Dispose ();
}
stream = new FileStream (dbPath, FileMode.Open);
if (stream.Length != 0) {
materialDB = serializer.Deserialize (stream) as MaterialDB;
stream.Close ();
}
stream.Dispose ();
}
保存到文件
public void SaveItems () {
FileStream stream = new FileStream (dbPath, FileMode.Create);
serializer.Serialize (stream, materialDB);
stream.Close ();
stream.Dispose ();
}