Binary Serialization: Creating a File


using UnityEngine;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Generic;

class PlayingCards : MonoBehaviour
   void Awake()
      #if UNITY_IPHONE
         Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");
   void Start ()
      print(Application.persistentDataPath + "/Example.dat");

   void CreateFile()
      BinaryFormatter bf = new BinaryFormatter ();
      FileStream file = File.Create(Application.persistentDataPath + "/Example.dat");
      Cards card = new Cards();
      bf.Serialize (file, card);
      file.Close ();

class Cards
   public List<string> questions = new List<string>();
   public List<string> answers = new List<string> ();
   public List<int> questionSizes = new List<int> ();
   public List<int> answerSizes = new List<int> ();

Probably the best two things about Unity are that it’s free and that there’s a fantastic asset store with tons of useful assets including serialization assets. There are some more economical options as well as some really beefy packages that will probably handle everything you’ll ever need to do. However, serialization is quite simple. In order to create a file, you just need 5 lines of code and a basic understanding of how it works. Here are some points to consider when implementing binary serialization:

  • As always make sure you’re using the necessary namespaces.
  • If you’re developing for iPhone, you may experience some AOT/JIT compilation issues.  If you do, include a preprocessor directive indicated on lines 11 and 13 and use Environment.SetEnvironmentVariable() with the necessary arguments.
  • If you’d like to see where the file is and if it was successfully created or not, simply print Application.PersistenDataPath to see the exact location on your computer.
  • At the moment I can’t think of a reason you’d ever want to hardcode a file name but I did so here for the sake of simplicity.
  • Whatever you are going to serialize, make sure it’s serializable as indicated on line 31.