I'm trying to create a blender script that will move my selected objects to a new .blend file and then link those specific objects back into the original file.
This would be extremely useful to me and my workflow. Since my Blend files can get kind of cluttered and I figured it would be really mice to be able to parse and organize them.
I've tried the following code but I had problems with the handler methods. For some reason I can't get the original Blend file to link back the objects.
... I apologize in advance since I am new to python, and blender scripts...
Here's the code:
import bpy
from bpy.app.handlers import persistent
filep = bpy.data.filepath
#Move chosen objects to a collection
collection = bpy.data.collections.new( "link" )
bpy.context.scene.collection.children.link(collection)
for obj in bpy.context.selected_objects:
for coll in obj.users_collection:
# Unlink the object
coll.objects.unlink(obj)
collection.objects.link( obj )
bpy.context.view_layer.active_layer_collection = bpy.context.view_layer.layer_collection.children[collection.name]
bpy.ops.wm.save_as_mainfile(filepath=filep)
#Create a New File with isolated objects...
bpy.ops.wm.save_as_mainfile('INVOKE_AREA')
for c in bpy.data.collections:
if c.name != collection.name:
bpy.data.collections.remove(c)
for a in bpy.data.objects:
f = False
for b in bpy.context.selected_objects:
if a == b:
f = True
if f == False:
bpy.data.objects.remove(a, do_unlink=True)
#Create Handler: linking objects back to Main File
name = collection.name
h = bpy.data.filepath
g = bpy.path.basename
@persistent
def load_handler():
bpy.ops.wm.link(directory= h + "/Collection/", filepath= g, filename=name)
bpy.app.handlers.load_post.append(load_handler)
#open original file
bpy.ops.wm.open_mainfile(filepath=filep)