Saving’s mesh at runtime as an OBJ in Unity

For anyone who’s wondering how to save the meshes generated by, it’s pretty straightforward. I’ve seen a few people asking and no definitive answer, so thought I’d write it up in case anyone searching for this found it useful.

The steps are basically:

  1. Combine the chunks into one mesh.
    I used Unity’s built-in Combine Meshes. You can see a sample of the code here, which I adapted.
  2. Save the mesh locally.
    I used obj-unity3d to save the mesh as an obj to Application.persistentDataPath.
  3. Access the mesh.
    Currently is iOS only, so plug your iOS device in, open XCode, and do the following:
    Window>Devices and Simulators>Select your App> Press the cog>Download container > Save > Navigate to the container >Right click >Show package contents>App Data>Documents. Your file will be there!
    You could also upload the local OBJ to a cloud storage solution for easier access. I did this using Firebase, but that’s a post for another time.

A hacky code sample that might help you out:

//Get a reference to the SDMesh
SDMesh sdMesh = FindObjectOfType<SDMesh>();

//combine the meshes
MeshFilter[] meshFilters = sdMesh.GetComponentsInChildren<MeshFilter>();
CombineInstance[] combine = new CombineInstance[meshFilters.Length];
int i = 0;
while (i < meshFilters.Length)
combine[i].mesh = meshFilters[i].sharedMesh;
combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
Mesh combinedMesh = new Mesh();

//save the mesh
OBJData data = combinedMesh.EncodeOBJ();
string filepath = Application.persistentDataPath + "/Obj_" + UnityEngine.Random.Range(0, 10000) + ".obj";
var lStream = new FileStream(filepath, FileMode.Create);
OBJLoader.ExportOBJ(data, lStream);

Originally published at on November 24, 2018.

Leave a Reply

Your email address will not be published. Required fields are marked *