I am using this code which works very well for one object. I select Object_A and it moves to the collection MyCollection. If I select two or more objects, how would I change the code?

obj = bpy.context.window.scene.objects['Protrusive']
bpy.context.view_layer.objects.active = obj
A = bpy.context.object
A_old_coll = A.users_collection
terrain_coll_name = "MyCollection"
if terrain_coll_name not in bpy.data.collections:
    terrain_coll = bpy.data.collections.new(name=terrain_coll_name)
    terrain_coll = bpy.data.collections[terrain_coll_name]


for ob in A_old_coll:

1 Answer 1


You just have to .unlink(object) each object from all linked collections and then .link(object) each object to your target collection.

Example on how to move all objects in selection to MyCollection:

enter image description here

import bpy

C = bpy.context

# List of object references
objs = C.selected_objects

# Set target collection to a known collection 
coll_target = C.scene.collection.children.get("MyCollection")

# Set target collection based on the collection in context (selected) 
#coll_target = C.collection

# If target found and object list not empty
if coll_target and objs:

    # Loop through all objects
    for ob in objs:
        # Loop through all collections the obj is linked to
        for coll in ob.users_collection:
            # Unlink the object

        # Link each object to the target collection
  • $\begingroup$ Sorry, I can't seem to get it to work. I have selected a few objects then run the code and nothing happens. $\endgroup$ Commented Apr 20, 2020 at 9:05
  • $\begingroup$ Make sure there is a collection called MyCollection as a sub-collection of the scene collection -> add a print(coll_target) before the check @MichaelTeiniker Btw: Wouldn't write an asnwer without testing it. More importantly try to understand the principle. $\endgroup$
    – brockmann
    Commented Apr 20, 2020 at 9:10
  • $\begingroup$ recommend coll_target = context.collection $\endgroup$
    – batFINGER
    Commented Apr 20, 2020 at 15:21
  • $\begingroup$ @brockmann this case is if the "MyCollection" belong to the Scene Collection, but how to make it work if the "MyCollection" is a child of some other collection? $\endgroup$ Commented May 11, 2021 at 8:30
  • $\begingroup$ @JuanCarlos just use the following statement for a collection named "CollectionXYZ": coll_target = bpy.data.collections["CollectionXYZ"] $\endgroup$
    – Andy
    Commented Feb 21 at 17:02

You must log in to answer this question.

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