0

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

Chris
  • 59,454
  • 6
  • 30
  • 84
DaTuDou
  • 41
  • 3

1 Answers1

1

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.

Chris
  • 59,454
  • 6
  • 30
  • 84
Gorgious
  • 30,723
  • 2
  • 44
  • 101