0
$\begingroup$
import bpy

def driver_func(val):
    activeobj = bpy.context.active_object

    if activeobj.name == "A":
        output = val * val
    else:
        output = val + 20

    return output

#add function to driver_namespace
bpy.app.driver_namespace['driver_func'] = driver_func

Thanks to RJG for the improvement. This script indeed runs in the scripting editor without errors, but when I add driver_func in the driver's editor as scripted expression to an object's transform (e.g. z-rotation) I get ERROR: Invalid Python Expression ...

The terminal message reads:

Traceback (most recent call last):
   File "<bpy driver>", line 1, in <module>
   File "/Users/.../Test.blend/TestPython", line 4, in driver_func
AttributeError: 'Context' object has no attribute 'active_object'
$\endgroup$
1
$\begingroup$

You could enable Use Self in the driver editor to get access to the object that the driver is used on. Then you would need to modify the arguments passed into function and use self to check for the name instead of trying to get the active object. The modified script look like this:

import bpy

def driver_func(self, val):
    if self.name == "A":
        output = val * val
    else:
        output = val + 20

    return output

#add function to driver_namespace
bpy.app.driver_namespace['driver_func'] = driver_func

Modify the expression to driver_func(self, var) or replace var with whatever your variable is called. Be aware that your current script increases the value very quickly.

Driver settings

I'm not an expert at Blender's drivers, so if somebody more experienced has a better solution, feel free to add another answer.


Alternatively you can access the active object through bpy.context.view_layer.objects.active as you've pointed out in the comments. Then the script would look like this:

import bpy

def driver_func(val):
    active_obj = bpy.context.view_layer.objects.active

    if active_obj.name == "A":
        output = val * val
    else:
        output = val + 20

    return output

#add function to driver_namespace
bpy.app.driver_namespace['driver_func'] = driver_func
| improve this answer | |
$\endgroup$
  • $\begingroup$ Thank you. Actually I don't want to access the object the driver is used on. The object with the driver is controlled by parameters of other objects via the function. I found a different solution, if one changes the syntax to activeobj = bpy.context.view_layer.objects.active it works. $\endgroup$ – Olafur Sep 15 '19 at 18:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.