Mesh Save and Load

Save and Load Mesh Data in Unity

I do have a hell of a fun with generative graphics; if you do too and you want to save some of your creations to a file at runtime and load them later on, here’s your today’s chocolate cake. i use this method especially where it takes time to generate a topology and loading it is a lot quicker than regenerating it.
Bear in mind

    we are not talking about exporting to some formats like FBX or DAE

but rather about dumping our mesh data (vertices, triangles, uvs, ..) to a file and read it later to become a Unity Mesh object. We will write the actual mesh data to a file in a binary format. Also, in this instance, we consider just the mesh part, leaving out materials and textures that may be connected to your MeshRenderer.
In other words, what we will save and load is a mesh topology.

Limitations:

  • Mesh must be below 65000 vertices
  • Deals with mesh (topology) only.

Serializable Mesh Info

To serialize out mesh data we need a sort of intermediary class that holds all data in basic types containers. In fact, in Unity and in general, complex types like Vector3 cannot be serialized and we have to work around it by storing 3 float values.

The class SerializableMeshInfo will be our serializable container for Unity’s mesh data.

SerializableMeshInfo.cs

Side note: Unity 5.5.2 introduced more non-allocating accessors to Mesh (GetBindposes, GetBoneWeights, GetColors, GetIndices, GetNormals, GetTangents, GetTriangles, GetVertices), that write into user-specified List. These can be used to access the Mesh data instead of accessing its arrays as above.

Save and Load with MeshDump and MeshUndump

Now that we have a completely serializable data structure that holds mesh data so that it can be written to the disk we can proceed to use it with the following two functions to save and load.