无法读取 Unity 5 中的序列化代码
本文关键字:序列化 代码 读取 Unity | 更新日期: 2023-09-27 17:56:19
所以,我试图做的是将浮点数和字符串保存到数据库中,以便我以后可以在持久的高分表中使用这些值。
我已经做到了能够保存数据的程度,并且我提供给 Save 函数的条目越多,文件就越大。所以我假设,这是有效的。
当我想反序列化文件以读取和构造记分表时,出现此错误:
无效转换异常:无法从源类型强制转换为目标类型。 loadHighScore.LoadFromFile () (at Assets/scripts/GameManager/loadHighScore.cs:40)loadHighScore.Start (at Assets/scripts/GameManager/loadHighScore.cs:18)
以下是两个脚本:
高分计数器:
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;
}
}
负载高分:
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 个小时,却无法弄清楚出了什么问题。
尝试将 PlayerData 类
移动到单独的文件中,否则这两个 PlayerData 类被视为独立,因此不兼容
编辑:为了澄清,请从 Unity 创建新脚本并将内容替换为以下内容:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System;
[Serializable]
class PlayerData
{
public int highScoreFinal;
public string playerName;
}
然后删除您拥有的这两个 PlayerData 类,因为您现在不需要它们