2017-02-12 52 views
3

試圖.dat文件轉換爲自己的類投對象類C#

level0 = (Level0) LoadObjInBinary(level0, "Level" + levelNumber); 

    public static object LoadObjInBinary(object myClass, string fileName) { 
     fileName += ".dat"; 
     if (File.Exists(FileLocation + fileName)) { 
      BinaryFormatter bf = new BinaryFormatter(); 
      FileStream file = File.Open(FileLocation + fileName, FileMode.Open); 
      myClass = bf.Deserialize(file); 
      file.Close(); 
      return myClass; 
     } else { 
      return null; 
     } 
    } 


Level() class 

    [Serializable] 
    public class Level0 { //Using this class to create Level.dat binary file 

     static int level = 1; 
     static int moves = 15; 
     static int seconds; 
     static int minScoreForOneStar = 1000; 
     static int minScoreForTwoStars = 1500; 
     static int minScoreForThreeStars = 2000; 

     static TargetObj[] targetObjs = {new TargetObj(Targets.Black, 10), new TargetObj(Targets.Freezer, 1), new TargetObj(Targets.Anchor, 2)}; 

     static Color[] colors = {Constants.grey, Constants.green, Constants.pink, Constants.brown, Constants.purple, Constants.lightBlue}; 

     static Cell[,] levelDesign; 

     //the rest is Properties of Fields 

    } 

問題:LoadObjInBinary返回null。該文件的路徑是正確的,類也相匹配,但不知道爲什麼「(0級)對象」不工作...

感謝

+0

還使用了BinaryFormatter的序列化'Level0'類型?只是爲了科學:你可以用'return new Level0();'替換'return null;'。我想驗證路徑是否正確。 – rene

+1

沒有什麼改變,文件存在,它確實返回對象,但不能將其轉換爲Level0()並且是我使用BinaryFormatter來序列化 – MJahongir

+0

您可以提供Level0類的其他信息。它是否標記爲可序列化?它是否包含也是自定義類型的其他成員? – Vect0rZ

回答

2

感謝您提供LEVEL0類。

問題是,靜態字段永遠不會被序列化,因爲它們不屬於您的實例化對象,它們是全局的。

因爲我認爲你需要它們是靜態的,所以它們可以從應用程序的所有部分訪問,快速解決方法是用非靜態成員創建另一個類,然後序列化 - 反序列化它,並分配它是Level0的全局靜態實例的值(無論您在哪裏使用它)。

[Serializable] 
class Level0Data 
{ 
    int level = 1; 
    int moves = 15; 
    int seconds; 
    int minScoreForOneStar = 1000; 
    ... 
} 

然後,在序列化和反序列化之後,您可以執行以下操作。

Level0Data deserializedObject = (Level0Data) LoadObjInBinary(..); 
Level0.level = deserializedObject.level; 
Level0.moves = deserializedObject.moves; 

你一定要確保Level0.level,移動和所有其他成員都是公開的,或至少公開地提供給其它方式修改。

Additionaly你必須確保

class TargetObj{} 
class Cell{} 

也被標記爲Serializable,否則他們將不會被寫入該文件,也沒有關於他們的任何反序列化的信息。

編輯

在這裏你可以找到默認可序列化類型的團結所有支持:

Unity SerializeField

+1

thanx很多,它的工作,也是我加入不是可序列化的顏色[]我改變它有顏色十六進制值的字符串[] – MJahongir

+1

太棒了!關於顏色,是的,我認爲只有最新版本的Unity支持它的原始序列化。 – Vect0rZ