无法打开二进制文件 Unity



这就是我在开发工具包中保存leveldata的方式。这在开发程序中运行(
并且数据也可以在开发工具包中正确恢复。

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

这就是我在资源中移动文件后尝试打开数据的方式。(这在实际游戏中运行(请参阅行 \错误

NullReferenceException:对象引用未设置为实例 object GameControl.LoadLevelData (( (at Assets/GameControl.cs:70( GameControl.Awake (( (at 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.请注意[Serializable()]中的()。删除它。那应该是[Serializable].另一位用户提到这是有效的。确保执行#2。

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

例如,DevData类应该位于其自己的名为DevData.cs的文件中。 您还应该为 Wave 和将序列化的其他类执行此操作。


最后,如果这不能解决您的问题,这是一个已知问题,在 Unity 中使用时BinaryFormatter会导致很多问题。您应该放弃它并改用 Json。看看这篇文章,它描述了如何使用Json来实现这一点。

最新更新