5
$\begingroup$

I am trying to detect when the active scene changes. Initially I tried using the message bus system to subscribe to bpy.types.Window, "scene"

Like this:

def callback():
  print("changed")

owner = object()
subscribe_to = bpy.types.Window, "scene"
    
bpy.msgbus.subscribe_rna(
  key=subscribe_to,
  owner=owner,
  args=(),
  notify=callback,
  options={"PERSISTENT"}
)

This works when changing scenes manually or changing scenes from Python. However it does not trigger when a new scene is created and Blender switches to it automatically.

I then tried to add an application handler to the depsgraph_update_post event and compare the number of scenes before and after the update as suggested in the comments here (Blender Python: Detect New Scene?). Unfortunately the app handler does not trigger either. I tested the configuration by adding an object to the scene and that triggers the handler.

Is this expected behavior? How can I detect the automatic scene change when a new scene is created.

Thanks in advance.

$\endgroup$

1 Answer 1

0
$\begingroup$

Not a clean solution but this does react to scene creation: bpy.app.handlers.frame_change_post.

from bpy.app.handlers import persistent

@persistent
def on_frame_changed(scene, depsgraph):
    screen = bpy.context.screen
    if screen and (screen.is_animation_playing or screen.is_scrubbing):
        return

    print("Possibly scene swapped or created.")


try:
    # Skip if handler installed
    bpy.app.handlers.frame_change_post.index(on_frame_changed)
except ValueError:
    # Install
    bpy.app.handlers.frame_change_post.append(on_frame_changed)

$\endgroup$

You must log in to answer this question.

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