I'm trying to serialize a 3D jagged array of a class I've created, and I'm getting the following error from within BinaryFormatter
when I call binaryFormatter.Serialize()
:
NullReferenceException: Object reference not set to an instance of an object System.Runtime.Serialization.Formatters.Binary.ObjectWriter.GetAssemblyNameId (System.String assembly) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectWriter.cs:812) System.Runtime.Serialization.Formatters.Binary.ObjectWriter.GetAssemblyId (System.Reflection.Assembly assembly) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ObjectWriter.cs:807)...
The most obvious potential issue, would be that the jagged array isn't correctly and fully initialized, but that isn't the case. I've tested multiple initialization strategies, and, if it wasn't properly initialized, the application would have had problems way before serialization.
It's important to note, after the jagged array is initialized, I loop through the array and instantiate ExampleClass() for each index.
I'm doing this in Unity 3D.
What am I missing?
BinaryFormatter binaryFormatter = new BinaryFormatter();
FileStream fileStream = File.Create(Application.persistentDataPath + "/data.dat");
// Initialize the jagged array
ExampleClass[][][] exampleClassArray = new ExampleClass[32][][];
for (int i = 0; i < exampleClassArray.Length; i++)
{
exampleClassArray[i] = new ExampleClass[32][];
for (int j = 0; j < exampleClassArray[i].Length; j++)
{
exampleClassArray[i][j] = new ExampleClass[32];
}
}
// Populate the jagged array
for (int i = 0; i < 32; i++)
{
for (int j = 0; j < 32; j++)
{
for (int k = 0; k < 32; k++)
{
exampleClassArray[i][j][k] = new ExampleClass();
}
}
}
binaryFormatter.Serialize(fileStream, exampleClassArray);
fileStream.Close();