Hi! I need to create a script that runs a function when the objects selection in scene changes.
I tried with an handler, that on each scene update compare the last selection with the new one, and if it is different it runs the function. I stored the selection in an array, but when I compare it with bpy.context.selected_objects it tells me that the array is referenced before assignemnt, even if the assignement is before it in the code.
Here’s the code so far. Probably with the handlers the things works different than usual.
Any idea for this?
What I’m trying to achieve is that when I select an object, Blender selects all other objects with the same property. Any other ways to do this?
<br>
<br>Yes, and even if I’m curious to see how to do that, I think that selection could change for other reasons than clicks, so I prefer to compare the selection itself instead of its lenght or when the click happens.
Can you explain me the purpose and the reasons behind the function add_handler?
Can I do the comparison of old and new selection in the handler def and calling the function in it like so?
def assembly_handler(scene):
global last_selection, need_to_update
if sel_objs != last_selection:
last_selection = sel_objs
SelectAssembly()
I made some corrections to the code, also now it’s far better and more simplified.
Can I do the comparison of old and new selection in the handler def and calling the function in it like so?
Good idea to compare the lists directly, it seems that it works, however you won’t need to use sel_objs at all since you can get the selected objects right from the context.
import bpy
import time
last_selection = []
sel_objs = bpy.context.selected_objects
"""
# OLD CODE
def assembly_handler(scene):
global last_selection, sel_objs
# At the very first loop this
# will be valid because lists are not the same
if sel_objs != last_selection:
# Now lists are the same
# the if loop will never run again
last_selection = sel_objs
print("Updated", time.time())
"""
def assembly_handler(scene):
global last_selection
if bpy.context.selected_objects != last_selection:
last_selection = bpy.context.selected_objects
print("Updated", time.time())
bpy.app.handlers.scene_update_post.clear()
bpy.app.handlers.scene_update_post.append(assembly_handler)
Can you explain me the purpose and the reasons behind the function add_handler?