Scripted driver (custom function) only takes effect after selecting driven object

Hello,

I wrote a simple custom function which I use as a driver. The script looks as follows:

import bpy
import mathutils

def custom_expression():
    origin = mathutils.Vector((0,0,0))
    return (origin-bpy.data.objects[2].matrix_world*bpy.data.objects[2].data.vertices[0].co).length
   
bpy.app.driver_namespace['custom_expression'] = custom_expression

The function custom_expression does not make much sense , but it’s simple and demonstrates my problem: it calculates the distance between the origin and a vertex of objects[2] in the scene (I know I could simply solve this for example using an Empty at (0,0,0) and use a “Driver variable type” of “distance”, but this will not help me, since my custom_expression is much more complex and can only be solved using a custom scripted expression.

Now, when I use this function as a driver for, let’s say, the rotation of another object, then the object’s rotation will not immediately update when I modify the position of objects[2]. For it to update, I need to select the object, enter Edit mode, and leave Edit mode again (it renders correctly, however).

How can I achieve that the rotation is updated immediately when I change the position of objects[2].

Please note, that the code I provided is just a demonstration for a much more complex script. I need a general solution to my problem, not one specific to the code I provided.

I hope this makes sense. I attach a .blend file. To test it, press Alt-P in the Text Editor, then press “Update Dependencies” in the Drivers toolbox. Move the object called “Objects[2]”. The rotation of object “Driven_Rotation” is only updated after selecting it, switching to Edit mode and back to Object mode.

custom_scripted_expression.blend (469 KB)

Any hints are more than appreciated.

blackno666

I found an easy solution which works for me:

In the Drivers panel, I added a variable as “Single Property”.
The “Prop:” is Objects[2]
and the path is any valid path of that object, e.g. location[0]

This builds a dependency between Objects[2] and the driver. As soon as Objects[2] is modified in any way, the driver will be updated and affects the rotation of Driven_Rotation immediately.


Instead of a “Single Property” “Transform Channel” could also be used. Ob/Bone: is Objetcs[2] and Type and Space is any arbitrary value.

I hope this makes sense. For me it does.

Blackno666