0
$\begingroup$

I have many collections in the scene. There are many models with the same prefix in the collection. I try to merge objects with the same prefix in each collection.

My idea is:

  1. Select a collection to hide other collections

for i in bpy.data.collections:
    
    i.hide_viewport = True

2.Select objects according to prefix. Prefix example 'Assembled','Basic'

for i in bpy.data.collections:

  i.hide_viewport = False

  bpy.ops.object.select_pattern(pattern='Assembled'+"*")

  bpy.ops.object.join() #Warning: Active object is not a selected mesh

  bpy.ops.object.select_all(action='DESELECT')

My question is:How do I turn one of the selected objects into an active object In addition, I feel there is something wrong with my thinking. Can I have a simpler solutionenter image description here

enter image description here

$\endgroup$

1 Answer 1

1
$\begingroup$

You can use a context override

  • Loop over all collections
  • Gather collection's objects beginning with the prefix
  • Join using a context override

.

import bpy

prefix = "Assembler"

for col in bpy.data.collections:
    objects_to_join = [o for o in col.objects if o.name.startswith(prefix)]
    if len(objects_to_join) > 1:  # we don't want to join if there is no object or only one object to join
        bpy.ops.object.join(
            {
                "selected_editable_objects" : objects_to_join,
                "active_object": objects_to_join[0]
            }
        )

Note: this assumes there are only MESH objects which names start with the prefix.

$\endgroup$
5
  • $\begingroup$ maybe this note makes more sense in your answer? ;) $\endgroup$
    – Chris
    Nov 19, 2021 at 11:40
  • 1
    $\begingroup$ @Chris Sure thanks for feedback :) $\endgroup$
    – Gorgious
    Nov 19, 2021 at 11:54
  • $\begingroup$ Thank Chris and Gorgious,Successfully solved my problem $\endgroup$
    – DaTuDou
    Nov 22, 2021 at 1:11
  • $\begingroup$ bpy.ops.object.join( { "selected_editable_objects" : objects_to_join, "active_object": objects_to_join[0] } ) “{.......}” Do you have any information to see?thank you very much $\endgroup$
    – DaTuDou
    Nov 22, 2021 at 1:32
  • $\begingroup$ Do you mean, to see the parameters you have to pass in to the override ? $\endgroup$
    – Gorgious
    Nov 22, 2021 at 7:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.