8

I have automated the task of parenting in Blender with Python. The code affects the relation parent according to the two last characters of the names of the objects. example:

obj1.name = Cube.01
obj2.name = Suzanne.01

If obj1 is in the group "children" and obj2 is not in the group "children" : obj2 is the parent of obj1. My code works, but without keeping children's transformation. How can I do to keep the children's transformation?

import bpy

for obj1 in bpy.context.selected_objects:    
    if obj1.name in  bpy.data.groups["Children"].objects:
    a = obj1.name[-2:]

    for obj2 in bpy.context.selected_objects:
            if obj2.name not in  bpy.data.groups["Children"].objects:
                b = obj2.name[-2:]
                if a == b:                       
                   obj1.parent= obj2
Ray Mairlot
  • 29,192
  • 11
  • 103
  • 125
Logiquefloue
  • 219
  • 3
  • 7

2 Answers2

18

You have to set the inverse matrix of the child to clear the initial transformation of the parent at parenting moment :

obj1.parent= obj2
obj1.matrix_parent_inverse = obj2.matrix_world.inverted()
Chebhou
  • 19,533
  • 51
  • 98
  • This doesn't seem to work for clearing the scale. Any thoughts on how to do that? – Rich Colburn Aug 16 '22 at 22:04
  • this will not keep transform, at least in blender 3.1 when your parent is a curve. if you find the solution could you please post it here https://blender.stackexchange.com/questions/273079/parenting-to-a-curve-with-python-leads-to-unexplained-results – Harry McKenzie Aug 27 '22 at 02:18
2

An additional note to Chebhou's answer and for other community members searching for answers related to keeping the child's transform when the parent object is a Curve. The solution comes from this thread: If your parent object is a Curve, you need to set the use_path property of the curve's data to False.

curve.data.use_path = False
obj.parent = curve
obj.matrix_parent_inverse = curve.matrix_world.inverted()
Harry McKenzie
  • 10,995
  • 8
  • 23
  • 51