I am writing a game in which I need to procedurally generate a mesh. The AssetDatabase class is available to me if this mesh is generated in the Editor and save it into the assets folder, but the meshes I am working with are specific to a specific game instance, and would be stored in the user’s save game directory. How do I save the generated mesh? I don’t need to save the mesh in any exchangeable format, just something Unity can read/write.
According to most posts, I’d create some kind of serializer but has Unity 5 introduced any new capabilities?
The easiest is most reliable way is to not serialize the mesh itself, but rather the data that is used be the mesh generating algorithm to generate it. This could be, for example, a 2-dimensional int array for a tile-based mesh. The array is flattened so it can be serialized, and then serialized and saved to a file. To load it, the file is loaded, deserialized, and then the array is made multidimensional again and the resulting 2-dimensional array is then used by then mesh generator to create teh mesh anew.
Here’s one possible asset to save and load data:
As in THIS article
the trick is to create a serializable mesh class that holds all mesh parts into serializable values and as it’s System.Serializable it can be serialized and written to a binary file using a BinaryFormatter.