1
$\begingroup$

I have this script which should count all the selected objects in the scene, but it doesn't. It cannot count the 6 monkeys that are part of a collection instance.

Can you help me?

import bpy

sel = bpy.context.selected_objects

obj = []
for o in sel:
    obj.append(o)

tot = len(obj)
print("There are %s selected monkeys!" %(tot))

$\endgroup$

1 Answer 1

2
$\begingroup$

You can use Object.instance_collection to get the reference to the original collection per object and iterate through Collection.objects. Recommend use the python console to figure out:

>>> C.object
bpy.data.objects['Collection']

>>> C.object.instance_type == 'COLLECTION'
True

>>> len(C.object.instance_collection.objects)
3

Basic demo on how to get all objects of a collection instance:

import bpy

C = bpy.context

objs = []
if C.object.instance_type == 'COLLECTION':
    for ob_col in C.object.instance_collection.objects:
        objs.append(ob_col)

print ("{} objects in collection instance".format(len(objs)))
print (objs) # Print object references

Basic demo on how to append all object names in selection as well as the object names of the selected collection instances to one list and and count the items:

import bpy

C = bpy.context

objs = []
for ob in C.selected_objects:    
    if ob.instance_type == 'COLLECTION':
        for ob_col in ob.instance_collection.objects:
            objs.append(ob_col.name)
    else:
        objs.append(ob.name)

print ("{} objects in selection".format(len(objs)))
$\endgroup$

You must log in to answer this question.

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