How to call a function when something is deselected or deselected?

I want when a user is selecting/deselecting an object to do something.

I’m working on an alignment tool (free to use) and I manage to make almost everything work.

If you select several objects and click align x or rotate x, it will align rotation/scale/dimension/move

But I can’t figure out how to hook into select/deselect event so that I can automatically align objects based on what is checked.

here is a demo of what I done so far

So if I understand correctly, the goal is that the action of selecting an object, automatically aligns it with a predetermined target?

If so, it might be better to use a modal operator and deliberately enter/exit alignment states instead of hooking into selections. The main reason is you don’t want to listen to events when a user does a selection completely unrelated to the addon.

Blender doesn’t expose selection events to python. The closest you can get currently is monitoring the depsgraph for selection changes using a callback placed in

bpy.app.handlers

and specifically either depsgraph_update_pre or depsgraph_update_post depending on your implementation.

In general I don’t recommend subscribing to depsgraph changes because they go off every time something in the scene is changed, but if it’s made clear to the user that something is active (eg. show text in viewport), then it would address the issue of having a noisy callback active.

1 Like

Thank you!, I will go with depsgraph_update_post for now. The only problem left is how to trigger an event on undoing or redo.

So what I think I will do is find an event for when any key is pressed and then make sure I execute my function if selection changed based on selection signature I think

There is an app handler for undo and redo as well.

can you please tell me which one?

https://docs.blender.org/api/blender2.8/bpy.app.handlers.html?highlight=undo%20redo#module-bpy.app.handlers

1 Like