How can I drive a shape key with a custom property slider using only Python scripting?
I intend to do a facial rig setup based on blendshapes and I want to do all the curves - shape key connections by scripting.
Blender Stack Exchange is a question and answer site for people who use Blender to create 3D graphics, animations, or games. It only takes a minute to sign up.
Sign up to join this communityMake an object custom property to drive each shape
From an Old blenderartists thread adds a custom property to context mesh object for each of its mesh data shapekeys, and sets up a driver from property to shapekey.
import bpy
context = bpy.context
scene = context.scene
object = context.object
mesh = object.data
shape_keys = mesh.shape_keys
frame = scene.frame_start
scene.frame_set(frame)
# dictionary of shape_key fcurves keyed by data_path
fcurve_dict = {}
rna = object.get('_RNA_UI', {})
for key, keyblock in shape_keys.key_blocks.items():
if keyblock == shape_keys.key_blocks[0]:
print("keyblock %s assumed Basis and ignored" % key)
continue
# create a custom property for the key
rna[key] = {"name": key,
"min": keyblock.slider_min,
"max": keyblock.slider_max,
"description": "Shape Key %s" % key,
"soft_min": keyblock.slider_min,
"soft_max": keyblock.slider_max,
}
object[key] = keyblock.value
object["_RNA_UI"] = rna
# add a driver
fcurve = shape_keys.driver_add('key_blocks["%s"].value' % key)
driver = fcurve.driver
driver.type = 'SCRIPTED'
driver.expression = "shape"
var = driver.variables.new()
var.name = "shape"
var.type = 'SINGLE_PROP'
target = var.targets[0]
target.id_type = "OBJECT"
target.id = object.id_data
target.data_path = '["%s"]' % key
If for instance you wish to put properties on the armature
object = bpy.data.objects["Name of Armature Object"]
mesh = bpy.data.meshes["Name of Mesh with Shapekeys"]
Please note old code.. don't use object
as a variable name as its a reserved python keyword use ob
or obj
(for example) instead