I would really like to parent objects to bones using Python, but the only way I can find to do this is using bpy.ops.object.parent_set(type=‘BONE’). This doesn’t take any more parameters other than the parenting type though. It only parents the selected objects to the active bone.
import bpy print(' ####################### ') bpy.ops.object.select_all(action='DESELECT') bpy.ops.object.select_name(name='Cube', extend=False) bpy.ops.object.select_name(name='Armature', extend=True) bpy.ops.object.mode_set(mode='POSE') bpy.ops.pose.select_all(action='DESELECT') bones = bpy.context.object.data.bones pose_bones = bpy.context.object.pose.bones edit_bones = bpy.context.object.data.edit_bones for bone in pose_bones: bone.select = False for bone in bones: bone.select = False bpy.context.object.data.bones['Bone.005'].select = True bpy.context.object.pose.bones['Bone.005'].select = True for bone in pose_bones: if not bone.name == 'Bone.005': bone.select = False for bone in bones: if not bone.name == 'Bone.005': bone.select = False bpy.ops.object.parent_set(type='BONE')
The script above should deselect all bones in both object.pose.bones and object.data.bones (just to make sure), and then select a single bone, double checking by deselecting all bones except that single bone.
But if you deselect all bones but one through Python then run bpy.context.active_pose_bone or bpy.context.active_bone then regardless of the way that you set the bone.select values in Python, the last bone that was selected in the 3d view is still the active bone. :mad:
It appears to be impossible to choose which bone is the active bone using Python.
Just noticed a bug in bpy.ops.object.select_name() too… extend does the same thing when set to both True and False, it always extends the selection.
Perhaps there’s an oversight in the operators and bpy.ops.pose.select_name(name=‘STRING’,extend=‘BOOL’) is missing? The way to change the active object using Python is using bpy.ops.object.select_name(name=‘STRING’,extend=‘DOES_NOT_WORK’)
Am I missing something or is this a bug report in the making?
Try the script on the default scene with an armature chain and you’ll see that the parenting is always to the last bone selected by mouse even if it is subsequently deselected.