4
$\begingroup$

I'd like to create script that does something to the scene every time 3d cursor moves. So far all handlers I've checked fire only when some object on scene changes, except 3d cursor. If possible I'd like to avoid polling for it every second. My question is whether there is handler in Blender that fires every time 3d cursor location is changed.

$\endgroup$

1 Answer 1

5
$\begingroup$

Message Bus (bpy.msgbus)

https://docs.blender.org/api/current/bpy.msgbus.html

import bpy

def msgbus_callback():
    print("3D cursor location change to: ", bpy.context.scene.cursor.location)

owner = (bpy.types.View3DCursor, "location")

bpy.msgbus.subscribe_rna(
    key=owner,
    owner=owner,
    args=(),
    notify=msgbus_callback,
)

Since in some cases using Message Bus doesn't work, it is proposed to use Application Handlers (bpy.app.handlers)

https://docs.blender.org/api/current/bpy.app.handlers.html

import bpy
from bpy.app.handlers import persistent

last_loc = bpy.context.scene.cursor.location.copy()

@persistent
def on_depsgraph_update(dummy):
    if bpy.context.scene.cursor.location != last_loc:
        loc = bpy.context.scene.cursor.location
        print("3D cursor location change to: ", loc)
        last_loc[:] = loc

bpy.app.handlers.depsgraph_update_post.append(on_depsgraph_update)
$\endgroup$
4
  • 2
    $\begingroup$ Note that as per the documentation this will not work for changes directly in the 3D viewport (SHIFT + right click, SHIFT + S > Cursor to selected, etc) $\endgroup$
    – Gorgious
    Feb 20, 2023 at 12:15
  • $\begingroup$ Wow, thank you. Application Handlers do seem to work with SHIFT+right click $\endgroup$
    – sheerun
    Feb 23, 2023 at 13:14
  • $\begingroup$ ^^^^^^^^^^^^^^ it no longer works as of Blender 3.5.1 $\endgroup$
    – sheerun
    Jun 1, 2023 at 14:26
  • $\begingroup$ I recently tested on 3.6 and it still works. $\endgroup$
    – X Y
    Jun 2, 2023 at 0:54

You must log in to answer this question.

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