5
$\begingroup$

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?

bpy.data.objects['Object_A'].select_set(True)
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)
    bpy.context.scene.collection.children.link(terrain_coll)
else:
    terrain_coll = bpy.data.collections[terrain_coll_name]

terrain_coll.objects.link(A)

for ob in A_old_coll:
    ob.objects.unlink(A)
$\endgroup$

1 Answer 1

11
$\begingroup$

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
            coll.objects.unlink(ob)

        # Link each object to the target collection
        coll_target.objects.link(ob)
$\endgroup$
4
  • $\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$ 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
    Apr 20, 2020 at 9:10
  • $\begingroup$ recommend coll_target = context.collection $\endgroup$
    – batFINGER
    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$ May 11, 2021 at 8:30

You must log in to answer this question.

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