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:

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.


1 Answer 1


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)
  • 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, 2019 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, 2019 at 4:26

You must log in to answer this question.

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