5
$\begingroup$

I am currently using the "parent clear" operator with the 'CLEAR_KEEP_TRANSFORM' type to clear transformations when dealing with tens of thousands of objects (see below), but unfortunately, operators lead to a scene update and this loop is extremely slow for my use case. Is there any way to do this solely at the object level? After this, I delete all the empties, but deleting those without unparenting and keeping transforms will of course screw up their location... Thanks in advance!

print("Removing transforms")
listOfMeshes = [obj for obj in sceneCollection.objects if obj.type!='EMPTY']
for obj in listOfMeshes:
    objcounter+=1
    print("At "+str(objcounter)+"/"+str(len(listOfMeshes))+" Removing transforms: "+obj.name)
    bpy.context.view_layer.objects.active = obj
    bpy.ops.object.parent_clear(type='CLEAR_KEEP_TRANSFORM')
$\endgroup$
0

1 Answer 1

5
$\begingroup$
import bpy
from bpy import context as C, data as D

# make copies to not modify the iterator
# https://youtu.be/OSGv2VnC0go?t=1200
obs_matrices = [(o, o.matrix_world.copy()) for o in D.objects]

for ob, mat in obs_matrices:
    ob.parent = None
    ob.matrix_world = mat

More reading:

I want to unparent an object with python

Clear Parent and Keep Transformation

Possibly much faster¹

Consider that the operator you use accepts multiple objects, and so you can clear parents for them in one go, and hope the C implementation of the operator will turn out to be much faster than a Python loop:

for ob in sceneCollection.objects:
    ob.select_set(obj.type != 'EMPTY')

bpy.ops.object.parent_clear(type='CLEAR_KEEP_TRANSFORM')

Also, you can use a context override and avoid the loop with object selection:

import bpy
from bpy import context as C, data as D

listOfMeshes = [obj for obj in sceneCollection.objects if obj.type!='EMPTY']

with C.temp_override(selected_editable_objects=listOfMeshes):
    bpy.ops.object.parent_clear(type='CLEAR_KEEP_TRANSFORM')

¹ - The OP David Chinellato tested the 3 solutions in this answer and they're roughly equivalent speed-wise with 4.71, 4.88, 4.8 results in seconds for 1500 objects.

$\endgroup$
2
  • $\begingroup$ You could test the 3 solutions and comment on the speed of each, since you already have a setup ready to test. $\endgroup$ Commented Sep 24, 2022 at 9:37
  • 2
    $\begingroup$ Hi Markus, many thanks!!! I tried the three options. Here some numbers for a small 1500 object test: 1) Original: 69.2 seconds, 2) With matrix setting: 4.71s, 3) With operating on all objects: 4.88s, 3) context override: 4.80s. I have files with several thousand objects where this will make a huge difference. I kind of feel stupid that I didn't realize, though, that the operator could act on multiple objects at once!!! But I am super happy. Thanks!!!! $\endgroup$ Commented Sep 24, 2022 at 12:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .