You have to understand that the asset browser is a file browser under the hood. So the available elements in the given contexts are the same as the file browser.
Link to the context elements available to the asset browser
The context
in this case has a handy selected_asset_files
attribute you can use. It is stated it is a sequence of bpy.types.FileSelectEntry, a class which has a handy relative_path attribute. It will output the filepath relatively to the root of the current library.
The root of the current library can be inferred by either
- Using the current filepath if we're looking at the Current File library
- Using a User Library filepath if we're looking at a User Library.
The active library name can be fetched with context.area.spaces.active.params.asset_library_ref
.
Link to the docs
If the current library name is LOCAL
, it means we're looking at the current file. I have not tested what happens if a user library is named LOCAL
, but I assume it would somehow bug out ?
Then, from the asset library name, you can fetch the asset library filepath with context.preferences.filepaths.asset_libraries
which returns the container of all user libraries.
Link to the docs
Which gives us :
import bpy
from pathlib import Path
class PrintAssetPaths(bpy.types.Operator):
bl_idname = "asset.print_filepaths"
bl_label = "Print Filepaths"
@classmethod
def poll(cls, context):
return context.selected_asset_files
def execute(self, context):
current_library_name = context.area.spaces.active.params.asset_library_ref
if current_library_name == "LOCAL": # Current file
library_path = Path(bpy.data.filepath) # Will be "." if file has never been saved
else:
library_path = Path(context.preferences.filepaths.asset_libraries.get(current_library_name).path)
for asset_file in context.selected_asset_files:
asset_fullpath = library_path / asset_file.relative_path
if current_library_name == "LOCAL":
# For some reason the relative path stops at the ID container in local file
asset_fullpath /= asset_file.local_id.name
print(asset_fullpath) # Includes the path to the asset inside the .blend file
asset_filepath = asset_fullpath.parent.parent
print(asset_filepath) # This is the file explorer path
return {"FINISHED"}
def display_button(self, context):
self.layout.operator(PrintAssetPaths.bl_idname)
def register():
bpy.utils.register_class(PrintAssetPaths)
bpy.types.ASSETBROWSER_MT_editor_menus.append(display_button)
def unregister():
bpy.types.ASSETBROWSER_MT_editor_menus.remove(display_button)
bpy.utils.unregister_class(PrintAssetPaths)
if __name__ == "__main__":
register()
This will add a button to the header of the asset browser area and print out the filepaths of all selected assets when clicked.
