Moving selection to a Collection w Python?

Hi,

On a selected object or hierarchy, I’m trying to:

  • create a new Collection (works)
  • move the selection to the newly created Collection (doesn’t work)

From the dropdown menu we have bpy.ops.object.move_to_collection(collection_index=2)
But this only works by selecting a Collection from the list.
From the outrliner we have bpy.ops.outliner.collection_drop()

How does one ‘define’ the new Collection for moving the selection?

cheers!
rob

The answer is to avoid outliner operators at all cost. They really aren’t meant to be used in standalone scripts

import bpy
col = bpy.data.collections.new(name="My New Collection")
bpy.context.scene.collection.children.link(col)
for obj in bpy.context.selected_objects:
    if obj.name not in col.objects:
        col.objects.link(obj)

If you want to unlink the objects from their original collections first :

import bpy

col = bpy.data.collections.new(name="My New Collection")
bpy.context.scene.collection.children.link(col)
for obj in bpy.context.selected_objects:
    for other_col in obj.users_collection:
        other_col.objects.unlink(obj)
    if obj.name not in col.objects:
        col.objects.link(obj)
4 Likes

He awesome! Thanks!

Will try that asap.

have a great weekend! :slight_smile:

edit: Works great, always nice to see code here. :slight_smile:

edit 2: removed previous questions. Both snippets of code work, had some issues implementing it into my tools and simple typo took longer to bugfix. :wink:

@RobWu Awesome happy to help :slight_smile: Re you question edit, yes drag-and-dropping from the outliner unlinks from other collections and links to the dropped in collection, but if you hold CTRL it will just link the object to the dropped in collection (similar to the first snippet of code)

Hi!

yes, figured that out too!. I also added some extra code to yours, like adding a Collection color, and make the selection fully local when the selected object is a linked Collection.

Thanks again for the help. :slight_smile: