3

picture

I want to select all objects in nested collection then do some operations using script. How?

P. Scotty
  • 311
  • 1
  • 8

2 Answers2

3

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 children contains 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.
Marty Fouts
  • 33,070
  • 10
  • 35
  • 79
1

First i recommend you turn on python tooltips by going into Edit menu => Preferences and then ticking Python Tooltips checkbox

enter image description here

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.

enter image description here

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

enter image description here

Harry McKenzie
  • 10,995
  • 8
  • 23
  • 51
  • 2
    Note: "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