我有一個名爲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類的定義 –