Skip to content

Instantly share code, notes, and snippets.

@ashblue
Created December 24, 2023 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashblue/951c9c59ceb697fcedbc8d4ec0cab927 to your computer and use it in GitHub Desktop.
Save ashblue/951c9c59ceb697fcedbc8d4ec0cab927 to your computer and use it in GitHub Desktop.
Automatically parent bones in Blender 3D to objects matching the pattern. Useful for rigging robots and mechanical skeletons.
import bpy
def parent_object_to_bone_by_name(armature, obj):
# Remove the 'O' prefix from the object's name to find the corresponding bone
bone_name = obj.name[1:] if obj.name.startswith("O") else None
if bone_name and bone_name in armature.pose.bones:
target_bone = armature.pose.bones[bone_name]
# Store the original world matrix of the object
original_matrix = obj.matrix_world.copy()
obj.parent = armature
obj.parent_type = 'BONE'
obj.parent_bone = target_bone.name
# Restore the original world matrix to prevent moving the object
obj.matrix_world = original_matrix
else:
print(f"No corresponding bone found for object '{obj.name}'.")
armature = bpy.data.objects['Skeleton'] # Adjust if your armature has a different name
# Iterate over all selected objects
for obj in bpy.context.selected_objects:
if obj.type == 'MESH' and obj != armature:
parent_object_to_bone_by_name(armature, obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment