2
$\begingroup$

I have a blend file with hundreds of mesh objects as part of a kit bash pack.

I want to copy each mesh to its own file and turn those files into KPacks for Kit Ops addon.

To export each mesh into a new file I tried to use this code:

import bpy

base_path = "c:\\temp\\"

for idx, obj in enumerate(bpy.data.objects):
    bpy.data.libraries.write(f'{base_path}obj_{idx}.blend', {obj}, fake_user=True)

The problem is that in the files created by the script, only the data blocks are copied, there are no meshes created.

How can I copy each mesh to a new file? It would be very tedious to do that manually for hundreds of files.

$\endgroup$
3
  • 1
    $\begingroup$ Could simply libraries.write(fp, use_fake_user=True) to stop orphans. Seems over kill to add a collection for a one object file. If using collections would add multiple objects to collection then write collection to lib. $\endgroup$ – batFINGER May 21 '20 at 19:32
  • $\begingroup$ @batFINGER You're right, that does stop the data from being orphaned. I was mistaken though, I don't need to copy just the data, but actual mesh. I need to have the objects visible and editable. Seems that just copying the data block is not enough, I have to find a way to copy the entire mesh to a new file. I updated my question to reflect this. $\endgroup$ – Virgiliu May 21 '20 at 23:38
  • $\begingroup$ Can't find the link, sure this has been asked before. Will notice on opening a library file that there is no scene. In later versions a dummy scene is created, to which it is simply a matter of linking objects, or using script as answered below. $\endgroup$ – batFINGER May 22 '20 at 2:34
1
$\begingroup$

Found how to do it. The code I had was half the solution.

After creating a new file, executing the following script adds the mesh to a collection in the scene as I needed. It assumes there's no collection and only one data block in the blend file.

add_object.py

import bpy

collection = bpy.data.collections.new("Collection 1")
bpy.context.scene.collection.children.link(collection)
collection.objects.link(bpy.data.objects[0])
bpy.ops.wm.save_as_mainfile(filepath=bpy.data.filepath)

To execute the script, I executed this in a loop:

blender.exe  <path_to_new_blend_file> --background --python add_object.py
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.