【发布时间】:2016-07-12 04:05:14
【问题描述】:
所以,我要做的是将浮点数和字符串保存到数据库中,以便以后可以在持久高分表中使用这些值。
我已经到了能够保存数据的地步,而且我输入保存功能的条目越多,文件就越大。所以我假设,这行得通。
当我想反序列化文件以读取和构建评分表时,我收到此错误:
InvalidCastException:无法从源类型转换为目标类型。 loadHighScore.LoadFromFile () (at Assets/scripts/GameManager/loadHighScore.cs:40)loadHighScore.Start () (at Assets/scripts/GameManager/loadHighScore.cs:18)
这是两个脚本:
highscoreCounter:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class highscoreCounter : MonoBehaviour
{
public static highscoreCounter control;
public int highScoreFinal;
public string playerName;
void Update()
{
highScoreFinal = GetComponent<highscoreCalculator>().highScoreFinal;
playerName = GameObject.Find("LevelFinisher").GetComponent<finishLevel>().newPlayerName;
SaveToFile();
}
public void SaveToFile()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/highScore.dat");
PlayerData data = new PlayerData();
data.playerName = playerName;
data.highScoreFinal = highScoreFinal;
bf.Serialize(file, data);
file.Close();
}
[Serializable]
class PlayerData
{
public int highScoreFinal;
public string playerName;
}
}
loadHighScore:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class loadHighScore : MonoBehaviour {
public static loadHighScore control;
int highScoreFinal;
string playerName;
public GameObject playerEntry;
void Start () {
LoadFromFile();
}
public void LoadFromFile()
{
if (File.Exists(Application.persistentDataPath + "/highScore.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/highScore.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
playerName = data.playerName;
highScoreFinal = data.highScoreFinal;
print(playerName);
print(highScoreFinal);
}
}
[Serializable]
class PlayerData
{
public int highScoreFinal;
public string playerName;
}
}
对于这段代码,如果有人想知道的话,我遵循了 Unitys YT 频道上的序列化教程。
如果有人将我引导到正确的方向来解决这里的问题,我会非常有帮助,因为我已经看了大约 3 个小时,却无法找出问题所在。
【问题讨论】:
-
BinaryFormatter臭名昭著的是,如果底层数据结构发生变化,数据将无法解串。尝试切换到更宽松的序列化结构,如 XML 或 JSON。 -
您好 Scott,感谢您提供有关更改为 XML 的提示。不过,我想知道这里发生了什么,因为我不明白为什么会这样。干杯
-
我不想用最好存储在外部文件中的数据污染我的 PlayerPrefs。