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?
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)
@RobWu Awesome happy to help 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)
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.