4
$\begingroup$

I'm creating an addon in Blender using bpy. It's a side panel with a few buttons and input fields. To speed up development, I would like the addon to automatically clear the original scene (the default cube), open its side panel, and press a button when it is started. By "started," I mean debugging in VS Code. I suppose that means after registering or installing the addon? Is this doable?

I tried registering operator classes and various handlers, but it always ended up either not executing at all or causing problems in ops.py:

Exception has occurred: AttributeError '_RestrictContext' object has no attribute 'view_layer'

Do you have a small working example?

$\endgroup$

1 Answer 1

3
$\begingroup$

Addons are first loaded in a restricted Context where no view_layer exists that's why you get thrown that error. Instead, you can execute your script within a on_application_load callback registered using the bpy.app.handlers.load_post Application Handler like this:

import bpy
from bpy.app.handlers import persistent

def delete_all() -> None:
    scene = bpy.context.scene
    for obj in scene.objects[:]:
        for collection in obj.users_collection:
            collection.objects.unlink(obj)
        bpy.data.objects.remove(obj)
    bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)

@persistent
def on_application_load(a, b):
    print("Application load post handler", a, b)
    delete_all()

def register() -> None:
    bpy.app.handlers.load_post.append(on_application_load)

def unregister() -> None:
    bpy.app.handlers.load_post.clear()

In this example, all the objects in the scene are deleted and purged when you open Blender or run debug it using VSCode.

$\endgroup$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .