2017-08-03 110 views
2

這就是我如何將leveldata保存在我的開發工具包中(這在開發程序中運行)
而且數據能夠在開發工具包中正確恢復。無法打開二進制文件Unity

public void Savedata() 
{ 
    List<List<float>> tempfloatlist = new List<List<float>>(); 

    foreach (List<Vector2> ele in routes) 
    { 
     conversions.Vec2float temp = new conversions.Vec2float(); 
     tempfloatlist.Add(temp.conv2float(ele)); 
    } 

    BinaryFormatter binform = new BinaryFormatter(); 
    FileStream savefile = File.Create(Application.persistentDataPath + 
    "/DevData.bytes"); 

    DevData savecontainer = new DevData(); 
    savecontainer.routenames = routenames; 
    savecontainer.routes = tempfloatlist; 
    savecontainer.waves = waves; 

    binform.Serialize(savefile, savecontainer); 
    savefile.Close(); 
} 

這是我嘗試打開數據後,我搬進資源文件(運行在實際的遊戲),查看線路\ ERROR

的NullReferenceException:對象引用未設置爲一個實例 GameControl.Awake()(在資產/ GameControl.cs:26)

我怕我不打開文件:一個 對象GameControl.LoadLevelData()(70,在資產/ GameControl.cs)的正確的方式。

private void LoadLevelData() 
{ 

    TextAsset devdataraw = Resources.Load("DevData") as TextAsset; 
    BinaryFormatter binform = new BinaryFormatter(); 
    Stream loadfile = new MemoryStream(devdataraw.bytes); 
    DevData devdata = binform.Deserialize(loadfile) as DevData; 
    \\ERROR happens here, no correct data to be loaded in routenames.   
    routenames = devdata.routenames; 
    waves = devdata.waves; 
    routes = new List<List<Vector2>>(); 
    foreach (List<float> ele in devdata.routes) 
    { 
     conversions.float2vec temp = new conversions.float2vec(); 
     routes.Add(temp.conv2vec(ele)); 
    } 
    loadfile.Close(); 
} 

[Serializable()] 
class DevData 
{ 
    public List<List<float>> routes; 
    public List<string> routenames; 
    public List<Wave> waves; 
} 
namespace WaveStructures 
{ 
[Serializable()] 
public class Enemy 
{ 
    public int enemytype; 
    public int movementpattern; 
    public int maxhealth; 
    public int speed; 
} 
[Serializable()] 
public class Spawntimer 
{ 
    public float timer; 
    public int amount;  
} 

[Serializable()] 
public class Wave 

{ 
    public List<Enemy> Enemylist; 
    public List<Spawntimer> Enemyspawnsequence; 
    public int[] enemypool; 
} 
} 
+0

發佈錯誤和您想要序列化的類。 – Programmer

+0

我想我加了你所問的,我對編程相當陌生,所以隨時給予批評,我很高興學習。 –

+0

加載後檢查'devdataraw.bytes'是否爲空。此時註釋掉下面的代碼。 – Programmer

回答

2

串行器正在難以序列化數據。

有隻有兩個可能的解決方案嘗試:

1在[Serializable()] .Notice的()。刪除。那應該是[Serializable]另一個user提到這是有效的。一定要做#2。

。確保您要序列化的每個類都放在它自己的文件中。確保它不會從MonoBehaviour繼承。

例如,DevData類應該在其自己的文件DevData.cs中。你還應該爲Wave和你將要序列化的其他類做這個。


最後,如果這不能解決您的問題,這是一個衆所周知的問題是BinaryFormatter引起這麼多的問題,統一使用時。你應該放棄它並使用Json來代替。看看this的帖子,它描述瞭如何使用Json。

+0

謝謝你的幫助和耐心,先生,我現在就來看看。祝你有個愉快的一天。 –

+2

點1不是問題。 'Serializable()'完全有效。 –

+0

感謝您的澄清。這只是我以前從未見過在Unity中使用過。 – PassetCronUs