I am writing an addon that requires a function (update_focal_length) to be called each time the camera is moved. As a quick and easy way to solve this, I append this function to bpy.app.handlers.depsgraph_update_post and bpy.app.handlers.frame_change_post. This works very well.
However, after closing Blender and reopening it, I find that even though my addon registers, update_focal_length is not called upon scene change anymore. The code works great when I use the checkbox to manually un-register and re-register the addon.
In an attempt to solve this problem, I also tried appending update_focal_length to bpy.app.handlers.load_post and bpy.app.handlers.load_pre, but the behavior continues to be the same. Ideally, I would like this function to be called when a file is loaded, and continue to be called each time the scene changes after that.
Here is the relevant code:
def update_focal_length(self, context):
# for each camera with focal_lock enabled...
for camera in bpy.data.cameras:
if camera.focal_lock.enable_lock and camera.focal_lock.focus_object != None:
currentDistance = distance_to_plane(camera.focal_lock.focus_object)
camera.lens = currentDistance * (camera.focal_lock.focal_distance_ratio)
#...#
handlers = [bpy.app.handlers.depsgraph_update_post, bpy.app.handlers.frame_change_post, bpy.app.handlers.load_post, bpy.app.handlers.load_pre]
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.Camera.focal_lock = bpy.props.PointerProperty(type=FocalLockSettings)
for handler in handlers:
[handler.remove(h) for h in handler if h.__name__ == "update_focal_length"]
handler.append(update_focal_length)
def unregister():
for cls in classes:
bpy.utils.unregister_class(cls)
del bpy.types.Camera.focal_lock
for handler in handlers:
[handler.remove(h) for h in handler if h.__name__ == "update_focal_length"]
if name == "main":
register()
Any ideas on how I may achieve this effect without users having to un-register and re-register my addon each time? Thanks so much for the help!
