无法打开二进制文件Unity

时间:2017-08-03 06:35:31

标签: c# unity3d

这就是我在开发工具包中保存leveldata的方法。(这在dev程序中运行)
并且数据能够在开发工具包中正确恢复。

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.LoadLevelData()(在Assets / GameControl.cs:70)   GameControl.Awake()(在Assets / GameControl.cs:26)

我担心我没有正确地打开文件。

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;
}
}

1 个答案:

答案 0 :(得分:2)

序列化程序很难序列化数据。

尝试两种可能的解决方案:

1 。注意()中的[Serializable()]。删除它。那应该是[Serializable]另一个user提到这是有效的。一定要做#2。

2 。确保要序列化的每个类都放在自己的文件中。确保它不会从MonoBehaviour继承。

例如,DevData类应该位于名为DevData.cs的文件中。你也应该为Wave和你将序列化的其他类做这个。

最后,如果这不能解决您的问题,那么BinaryFormatter在Unity中使用时会导致很多问题,这是一个已知问题。你应该放弃它并使用Json代替。请查看this帖子,其中介绍了如何使用Json。