0
$\begingroup$

Can anyone tell me how I can choose an arbitrary object from within a collection? My script leaves me with nothing active (or selected) at one point, but I need something to be active.

I have the collection name from this:

Coll = bpy.data.collections.get('Structure')

So I can do something like this:

if Coll:
   for obj in Coll.objects:
       obj.select_set(True)

Which makes each object active one at a time, leaving me with the last one active at the end of the loop. But that seems pretty heavy handed. There must be a neater way.

$\endgroup$
2
$\begingroup$

How does this work?

from random import choice

# deselect all:
for obj in Coll.objects: obj.select_set(False)
# choose one and select it:
rnd_obj = choice(Coll.objects)
rnd_obj.select_set(True)
$\endgroup$
  • 1
    $\begingroup$ Alternatively after choice and without deselecting all first for obj in Coll.objects: obj.select_set(obj is rnd_obj) and to set as active context.view_layer.objects.active = rnd_obj $\endgroup$ – batFINGER May 1 '19 at 12:41
  • 1
    $\begingroup$ Great! I've ended up with this, thanks to you both: import bpy Coll = bpy.data.collections.get('Collection') from random import choice rnd_obj = choice(Coll.objects) for obj in Coll.objects: obj.select_set(obj is rnd_obj) bpy.context.view_layer.objects.active = rnd_obj $\endgroup$ – edna May 8 '19 at 4:26

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.