Skip to content

Instantly share code, notes, and snippets.

@CGArtPython
Created November 24, 2024 21:13
Show Gist options
  • Save CGArtPython/f2b3759e27ba1b0eca112c528ebdf1c9 to your computer and use it in GitHub Desktop.
Save CGArtPython/f2b3759e27ba1b0eca112c528ebdf1c9 to your computer and use it in GitHub Desktop.
[Blender Python] Add an asset from the User Asset Library into the scene (vidoe explination https://www.skool.com/cgpython/make-a-button-to-add-a-model?p=abc92a32)
import pathlib
import bpy
def find_user_asset_dir():
user_lib_index = bpy.context.preferences.filepaths.asset_libraries.find("User Library")
if user_lib_index == -1:
return None
user_asset_lib = bpy.context.preferences.filepaths.asset_libraries[user_lib_index]
return user_asset_lib.path
class ImportManOperator(bpy.types.Operator):
bl_idname = "import_scene.man_asset"
bl_label = "Import Man Model"
def execute(self, context):
user_asset_dir = find_user_asset_dir()
if user_asset_dir is None:
self.report({'ERROR'}, "User Asset Library not found")
return {'CANCELLED'}
# TODO: Update the name of the blend file that you want to use
file_path = pathlib.Path(user_asset_dir) / "man.blend"
if not file_path.exists():
self.report({'ERROR'}, f"File not found: {file_path}")
return {'CANCELLED'}
with bpy.data.libraries.load(str(file_path)) as (data_from, data_to):
for name in data_from.objects:
if name == "man":
data_to.objects = [name]
scene = bpy.context.scene
# link the objects into the scene collection
for obj in data_to.objects:
if obj is None:
continue
scene.collection.objects.link(obj)
return {'CANCELLED'}
class VIEW3D_PT_my_custom_panel(bpy.types.Panel): # class naming convention ‘CATEGORY_PT_name’
# where to add the panel in the UI
bl_space_type = "VIEW_3D" # 3D Viewport area (find list of values here https://docs.blender.org/api/current/bpy_types_enum_items/space_type_items.html#rna-enum-space-type-items)
bl_region_type = "UI" # Sidebar region (find list of values here https://docs.blender.org/api/current/bpy_types_enum_items/region_type_items.html#rna-enum-region-type-items)
bl_category = "My Custom Panel category" # found in the Sidebar
bl_label = "My Custom Panel label" # found at the top of the Panel
def draw(self, context):
"""define the layout of the panel"""
row = self.layout.row()
row.operator("import_scene.man_asset", text="Add Man")
def register():
bpy.utils.register_class(ImportManOperator)
bpy.utils.register_class(VIEW3D_PT_my_custom_panel)
def unregister():
bpy.utils.unregister_class(VIEW3D_PT_my_custom_panel)
bpy.utils.unregister_class(ImportManOperator)
if __name__ == "__main__":
register()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment