Code for an add-on that appends objects

Hi everyone, I’m kinda new to coding and I’m trying to write a code that enables me to append in specific objects from within a blendfile saved within the add-ons zip file, I read that it is something like a relative path, but I’m absolutely terrible when it comes to paths so please can anyone give me a begginer level example of what I need to do to be able to append these objects please

Once an addon is installed you can locate the path using something like:

my_addon_path=os.path.join(bpy.utils.script_path_user(), "addons", "my_addon_folder")

If you stored your blend files in a subfolder just add the subfolder as well.

my_addon_blendfile_folder = os.path.join(my_addon_path, "my_blend_file_folder")

If you have multiple blend files in a subfolder you can then get the file names like:

my_blend_file_names = [fname for fname in os.listdir(my_addon_blendfile_folder) if fname.endswith(".blend")]

If appending easy items like objects in a collection:

# example full file path to blend file
fpath = "C:\\Blender Projects\\Assets\\Objects and Collections\\Fungi\\Mushrooms\\Agaricales\\yellow stainer.blend"

# Actual string names of collections in your blend file
collections = ["Objects", "Lights", ]

# link=False to append
with bpy.data.libraries.load(fpath, link=False) as (data_from, data_to):
    for obj in data_from.collections:
        data_to.collections.append(obj)

for coll in data_to.collections:
    for obj in coll.objects:
        # append to active view layer collection
        bpy.context.view_layer.active_layer_collection.collection.objects.link(obj)

Finally when using append operator:

https://docs.blender.org/api/current/bpy.ops.wm.html?highlight=append#bpy.ops.wm.append

Desciptions are a bit less intuitive.

blendfile = "D:/path/to/the/repository.blend"
section   = "\\Action\\"
object    = "myaction"

filepath  = blendfile + section + object
directory = blendfile + section
filename  = object

bpy.ops.wm.append(
    filepath=filepath, 
    filename=filename,
    directory=directory)
3 Likes