We can export any mesh from Blender to a file in OBJ format by selecting it and pressing the following items from the main menu: FIle – Export – Wavefront (.obj). If we need to split the scene into objects and export each of them to OBJ, this process can be easily automated.
Let’s write a small script that will allow us to simultaneously export all the meshes selected in the scene – each mesh into a separate file in OBJ format.
First, define the place where we will put the meshes exported from Blender. Let this be the same directory in which the .blend file with the current scene is located.
1 |
save_path = os.path.dirname(os.path.abspath(bpy.data.filepath)) |
The export to OBJ operator in Blender works with all selected objects at once. Therefore, to break the scene object by object, we need to save the list of selected objects and deselect them all. And then, selecting each mesh by this list one by one, export it to OBJ format.
Create a copy of the selected objects list,
1 |
objects = bpy.context.selected_objects[:] |
and deselect all of them.
1 |
bpy.ops.object.select_all(action='DESELECT') |
Next, let’s loop through the previously saved list of objects:
1 |
for ob in objects: |
If the object is a mesh, select it, execute the export to OBJ operator and deselect it again so that it is not exported again in the next iteration of the loop.
1 2 3 4 5 6 7 8 |
ob.select_set(True) bpy.ops.wm.obj_export( filepath=os.path.join(save_path, ob.name + '.obj'), export_selected_objects=True, ) ob.select_set(False) |
In the “filepath” parameter of the “obj_export()” operator, we pass the full path, including the extension, to save the mesh in OBJ format. In our example, this will be the path to the .blend file directory plus the file name and the “.obj” extension. As the file name, we use the name of the exported mesh, which we get from its “name” property.
After all, we can restore the original selection in the scene.
1 2 |
for ob in objects: ob.select_set(True) |
After executing this simple code, OBJ files will be created in the project directory, each of which will contain a separate exported mesh from the Blender scene.