我有一个名为Schematic的类,它存储了用于我的游戏的块的结构。我试图找到一种方法来使用BinaryFormatter保存和加载它们,但是我遇到了反序列化问题。当我反序列化时,我无法投射到我的源类型,而只能让我得到一个字段,一个整数的二维数组。Deserializtion返回类的字段而不是类
下面是示意图类的代码:
[Serializable]
public class Schematic
{
public static Schematic BlankSchematic = new Schematic("BLANK");
public int[,] Blocks;
public V2Int Size;
public V2Int Location = V2Int.zero;
public string Name;
//---PROPERTIES---
//lower is more rare
public int Rarity = 100;
//---END PROPERTIES---
public Schematic(string name)
{
Name = name;
}
public Schematic(string name, int[,] blocks)
{
Name = name;
ModifyBlockArray(blocks);
}
public void ModifyBlockArray(int[,] newBlocks)
{
Blocks = newBlocks;
Size = new V2Int(newBlocks.GetLength(0), newBlocks.GetLength(1));
}
}
而且我的方法在一个单独的类序列化和反序列化:
public void SaveSchematic(Schematic schem)
{
using (Stream stream = new FileStream(SchematicsDirectory + "/" + schem.Name + ".schem", FileMode.Create, FileAccess.Write, FileShare.None))
{
BinaryFormatter bf = new BinaryFormatter();
Debug.Log(schem.GetType());
bf.Serialize(stream, schem);
}
}
public void LoadSchematics(string dir)
{
BinaryFormatter bf = new BinaryFormatter();
DirectoryInfo info = new DirectoryInfo(dir);
FileInfo[] fileinfo = info.GetFiles("*.schem");
for (int i = 0; i < fileinfo.Length; i++)
{
FileStream fs = new FileStream(dir + fileinfo[i].Name, FileMode.Open);
object tempO = bf.Deserialize(fs);
Debug.Log(tempO + ", " + tempO.GetType());
Schematic temp = (Schematic)tempO;
SchematicsByName.Add(temp.Name, temp);
Schematics.Add(temp);
print("Loaded Schematic: " + temp.Name);
fs.Close();
fs.Dispose();
}
}
这是因为当我寻找到一个序列化的文件很奇怪,我看到其他领域和类名“示意图”。这里是一个小例子文件:
ÿÿÿÿ Assembly-CSharp Schematic BlocksSizeLocationNameRarity System.Int32[,]V2Int V2Int V2Int xy
TestSavingd
V2Int也被标记为可序列化。当我反序列化时,我返回Blocks数组而不是整个类,这真的很奇怪。任何帮助将非常感激。
这是我在这里的第一篇文章,很抱歉,如果我犯了错误。
我看不出有什么错误的地方我看,这是_ ** **非常好_对于第一个问题!做得好! - 我添加了Binary Serialization标签,认为可以很方便地指定已经在标签中的序列化类型。 –
请发布V2Int类的定义 –