Export Layers Script


Does anyone know how to export layers as individual files via script?
I have several dozens layers that I need to export as individual obj/fbx files, for easier import/update into the rendering software.


I did this the other day, just for meshes in stl format but if this helps you get started try changing ‘.stl’ for ‘.obj’
You will have to set the default options first manually by saving a single object with the parameters you want, then it should retain these for the others exported
Sorry it’s half in French !

import rhinoscriptsyntax as rs
import os

def export_mesh_by_layer(maillages):
    export_path = rs.BrowseForFolder(rs.WorkingFolder(), 
        'Exporter vers quel dossier?',
        'Export stl',)
    mesh_dict = {}
    for mesh in maillages:
        obj_layer = rs.ObjectLayer(mesh)
        print obj_layer
        if obj_layer in mesh_dict:
            mesh_dict[obj_layer] = [mesh, ]
    for layer, meshes in mesh_dict.iteritems():
        layer_export_name = layer.replace(':', '_')
        if meshes:
            meshids = ''
            for mesh in meshes:
                meshids += "_SelId " + str(mesh) + " "
                filename = os.path.join(export_path, layer_export_name + ".stl")
            command_str = "-_Export " + meshids + " _Enter " + chr(34) + filename + chr(34) + " _Enter " + "_Enter"
    return None

if __name__ == '__main__':
    export_mesh_by_layer(rs.GetObjects(filter = 32)) 

Also this discussion may help

Here are a couple of scripts to try out - they work in Windows, but not sure on Mac.

One file per object - named after the file name and sequentially numbered.
Objects/layers need to be visible and unlocked.
BatchExportOBJByObject.py (2.2 KB)

One file per layer - objects/layers need to be visible and unlocked.
BatchExportOBJByLayer.py (2.1 KB)

Let me know how either one of them works… They use standard meshing settings for non-mesh objects, which you can modify in the strings at the top of the script.


Unfortunately none of the scripts above worked on Rhino for Mac… :frowning:

OK, did you get any error messages?

All comments turn to errors.
Command lines, starting with “import”, like, “import rhinoscriptsyntax as rs” prompt the Import file command.

Hello - to run the script, use RunPythonScript - these are not command line macros.

To use a Python script use RunPythonScript, or a macro:

_-RunPythonScript "Full path to py file inside double-quotes"


Thanks this workedm with @Helvetosaur BatchExportOBJByLayer.py

Although the path in which the files was exported did not work on the mac.
My Test file is saved at the desktop, but the exported layers output was "/Users/MyUserName"and the file name came in as “Desk-00//2D_lns_01.obj”

SOLVED IT, by replacing:
#e_file_name = “{}-{}.obj”.format(filename[:-4], layer_name)
e_file_name = “{}-{}.obj”.format(filename, layer_name)

OK, that’s interesting, this works as expected on the Windows platform, so something is different on Mac with how filenames/paths are set up (not surprising). I’ll need to drag my Mac out and do some testing, I haven’t had much time these last couple of weeks… I can probably put in a switch that will make it work correctly on both platforms.

This morning I’m working on exporting my Rhino project for use in Unreal Engine. I’m attempting to use the batch export code you’ve provided above. After some modification with the help of chat gpt it’s successfully exporting each layer as a separate OBJ. However, the OBJs keep crashing Unreal Engine on import. I think it’s because the meshes aren’t triangulated, so I’ve been trying to triangulate on export from Rhino but haven’t been able to figure that out. If you might be able to offer any help I would be grateful.

import rhinoscriptsyntax as rs
import os

def GetOBJSettings():
e_str = "_Geometry=_Mesh "
e_str += "_EndOfLine=CRLF "
e_str += "_ExportRhinoObjectNames=_ExportObjectsAsOBJGroups "
e_str += "_ExportMeshTextureCoordinates=_Yes "
e_str += "_ExportMeshVertexNormals=_Yes "
e_str += "_CreateNGons=_No "
e_str += "_ExportMaterialDefinitions=_No "
e_str += "_YUp=_No "
e_str += "_WrapLongLines=Yes "
e_str += "_VertexWelding=_Welded "
e_str += "_WritePrecision=16 "
e_str += "_Enter _DetailedOptions "
e_str += "_JaggedSeams=_No "
e_str += "_PackTextures=_No "
e_str += "_Refine=_No " # Refining set to No can reduce mesh density
e_str += "_SimplePlane=_No "
e_str += "_AdvancedOptions "
e_str += "_Angle=25 " # Increased angle for less dense mesh
e_str += "_AspectRatio=6 " # Increased aspect ratio for less dense mesh
e_str += "_Distance=1 " # Increased distance for less dense mesh
e_str += "_Grid=0 " # Set grid to 0, will use the other parameters to determine density
e_str += "_MaxEdgeLength=10 " # Increased max edge length for less dense mesh
e_str += "_MinEdgeLength=0.1 " # Increased min edge length for less dense mesh
e_str += "_MaxAngle=60 " # Increased max angle to allow for less density
e_str += "_MinAngle=0 "
e_str += “_Enter _Enter”
return e_str

def BatchExportOBJByLayer():
# Get the current directory
dir = rs.DocumentPath()
if not dir:
dir = rs.BrowseForFolder(message=“Choose export directory”)
if not dir:
print(“No directory chosen.”)

obj_sett = GetOBJSettings()

for layer_name in rs.LayerNames():
    objs = rs.ObjectsByLayer(layer_name, True)
    if objs:
        # Create a filename based only on the layer name
        e_file_name = "{}.obj".format(layer_name)
        # Full path for the OBJ file
        full_path = os.path.join(dir, e_file_name)
        # Runs the export using the file name/path and settings
        rs.Command('-_Export "{}" {}'.format(full_path, obj_sett), True)