Reputation: 411
This is how I save leveldata in my development kit.(this runs in dev program)
And the data is able to be correctly restored in dev kit aswell.
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();
}
This is how I try to open the data after I moved the file in resources.(this runs in actual game) See line \ERROR
NullReferenceException: Object reference not set to an instance of an object GameControl.LoadLevelData () (at Assets/GameControl.cs:70) GameControl.Awake () (at Assets/GameControl.cs:26)
I fear that I am not opening the file correct way.
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;
}
}
Upvotes: 2
Views: 1030
Reputation: 447
The serializer is having hard time serializing the data.
There are just two possible solution to try:
1.Notice the ()
in your [Serializable()]
. Remove that. That should be [Serializable]
. Another user mention that this is valid. Make sure to do #2.
2.Make sure that every class you want to serialize is placed in its own file. Make sure that it does not inherit from MonoBehaviour
either.
For example, DevData
class should be in its own file called DevData.cs
. you should also do this for the Wave and other classes that you will serialize.
Finally, if this does not solve your problem, it's a known problem that BinaryFormatter
causes so many issues when used in Unity. You should abandon it and use Json instead. Take a look at this post which describes how to use Json for this.
Upvotes: 2