4
$\begingroup$

Is there any way to add if elif and else in drivers?

Given the way we do if and else, here are two examples out of few other things i tried to get the statement right but unable to do so:

var-3.5 if (var<0) var+3.5 elif (var>0) else 1

var-3.5 if (var<0) elif var+3.5 (var>0) else 1

And also if there's any other way to add multiple if/else similarly?

$\endgroup$
4
$\begingroup$

Nest the ternary conditional operator

(var + 3.5) if var > 0 else (var - 3.5) if var < 0 else 1

or for more detailed scripts

import bpy

def x(var):
    if var > 0:
        return var + 3.5
    elif var < 0:
         return var - 3.5
    else:
         return 1

bpy.app.driver_namespace["x"] = x

And then use x(var) as your driver expression.

$\endgroup$
3
  • $\begingroup$ Nesting the ternary conditional operator worked! Thankyou! Also thanks for the detailed version! $\endgroup$
    – netricsa
    May 26 '18 at 7:01
  • $\begingroup$ Thanks. One thing worth mentioning is the use_self option, which is the object being driven, passed as an argument, for example x(self) and var = self.location.x in the method instead of setting up a variable of the same in driver panel is worth looking into. $\endgroup$
    – batFINGER
    May 26 '18 at 8:20
  • $\begingroup$ Ah! I had tried self driver between translate and rotate not via the script but via the panel, and the object started going crazy.. will try the same thing with the script you mentioned. This will be awesome! Thanks again mate! $\endgroup$
    – netricsa
    May 26 '18 at 11:22
2
$\begingroup$

To use anything more than a simple python line in a driver you can define your own functions and add them to the driver namespace.

import bpy

def myfunc(var, amt):
    if var < 0:
        return var - amt
    elif var > 0:
        return var + amt
    return 1

bpy.app.driver_namespace['mydrvr'] = myfunc

Then in the driver expression you put mydrvr(var, 3.5)

$\endgroup$
1
  • $\begingroup$ Thanks! As for now nesting the ternary conditional operator as said by batFINGER worked but will keep this in mind :) $\endgroup$
    – netricsa
    May 26 '18 at 8:09

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.