I have tried to create code to serialize a Dictionary of <Vector2, Block>, where Block is a custom serializable class, loosely based off of this guide. I need to do this so that I can write this data to disk.

public static void SavePiece (string ObjectName, int index, Dictionary<Vector2, Block> VoxelSlice) {
    string saveFile = FileName (ObjectName, index);

    Stream stream = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None);
    formatter.Serialize(stream, VoxelSlice);

However, I am experiencing this error:

SerializationException: Type UnityEngine.Vector2 is not marked as Serializable.

I'm an absolute beginner to all things serialization and file writing, so I don't have much knowledge to go on, and I'm pretty stuck. I have a few questions:

  1. Is there any way to save lots of data without serializing?
  2. Can I somehow make Vector2 serializable?
  3. While I would rather not spend time re-working my code, would serialization work if I replaced Vector2 with a custom class?
  4. Can Dictionary be serialized at all anyway? A quick search for "unity serialize dictionary" seems to indicate that Dictionary can't be serialized.
  5. If Dictionary can't be serialized, what could I use instead to my store key/value pairs?
  • 1
    \$\begingroup\$ If I understand your case correctly, these entries correspond to regularly-spaced chunks of voxel data? If so, the floating point precision of Vector2 is an odd choice for the index, since they'll always be positioned at integer multiples of the block spacing. A custom int pair struct would give you precision to the nearest block over a much wider range, since you're not wasting bit pattens on fractions that you never use for placing a block. And you could make your int pair serializable while you're at it. :) \$\endgroup\$ – DMGregory Aug 13 '17 at 15:08
  • \$\begingroup\$ I'm not familiar with structs, how would this be done? I've only used classes before. \$\endgroup\$ – Aaron Franke Aug 16 '17 at 1:21
  • \$\begingroup\$ Pretty much the same, except that structs are value types instead of reference types (typically allocated on the stack instead of heap, pass/assign by value instead of by reference, compare via memberwise equality rather than reference equality). Google C# struct for an introduction to the core concepts. \$\endgroup\$ – DMGregory Aug 16 '17 at 3:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.