I want to select all objects in nested collection then do some operations using script. How?
- 311
- 1
- 8
-
Does this answer your question? https://blender.stackexchange.com/questions/144928/how-to-list-all-collections-and-their-objects – Harry McKenzie Apr 15 '22 at 04:07
-
@HarryMcKenzie I don't think it does because that question deals with all collections, but this one wants nested collections and the code is different. – Marty Fouts Apr 15 '22 at 15:24
-
@MartyFouts yeah you are correct – Harry McKenzie Apr 15 '22 at 15:31
2 Answers
First, this answer as good advice on how to develop Python scripts in Blender. I also recommend the tutorial "Scripting for Artists" that can be found on Blender's YouTube channel.
Assuming you have a specific collection and you want all of the collections it contains, this function select_from_collection will do what you want:
import bpy
def select_from_collection(some_collection):
""" Recursively select objects from the specified collection """
print(f"Selecting from {some_collection.name}")
for a_collection in some_collection.children:
select_from_collection(a_collection)
for obj in some_collection.objects:
print(f"Selecting object {obj.name}")
obj.select_set(True)
Example: selecting all objects in the active collection
select_from_collection(bpy.context.collection)
Note that this code will arbitrarily make the last object it encountered the active object.
There are two things you need to know about collections to understand this code and one thing about objects:
- To select an object, use
bpy.types.Object.select_set() - If a collection is nested, its field
childrencontains the names of all of the collections it contains. You need to walk this structure recursively to find all of the nested collections within your starting point. - If a collection contains objects, they will be listed in its field
objects. You have to iterate over that list to find all of the objects contained directly by the collection.
- 33,070
- 10
- 35
- 79
First i recommend you turn on python tooltips by going into Edit menu => Preferences and then ticking Python Tooltips checkbox
That way you can hover over the properties in the user interface and see python tooltips in your workspace so you don't have to remember them all.
And then checkout this thread here: How to list all collections and their objects? to get started. Also you can view the output of your script by going to Window => Toggle System Console
- 10,995
- 8
- 23
- 51
-
2Note: "Toggle System Console" is a Windows feature. On other OSes you get access to the system console in different ways. – Marty Fouts Apr 15 '22 at 15:06
-
@MartyFouts yes that is correct, im sure he will figure it out how to do it on unix and unix-like systems though :) – Harry McKenzie Apr 15 '22 at 17:04



