Where to find collection_index for moving an object?

Hey guys,

in preparing my addon for 2.8 I try to make the necessary collections and move or link objects into them via

bpy.ops.object.move_to_collection(collection_index=n)

I thought the collection_index=n would be the index of bpy.data.collections[n], which you can find by bpy.data.collections.find(“CollectionName”), but its not.

I figured out that bpy.data.collections are reordered alphabetically when a new collection is added or a collection is renamed. But the collection_index key of the move_to_collection function is an index given in order of collection creation. Can someone tell me how to access the collection_index value (preferably by collection name)?

Do not use operators for moving objects between collections. In general operators are not reliable to use in scripts, they are meant as end user tools. These indices correspond to a particular layout in user interface menus.

Instead use collection.objects.link() and collection.objects.unlink() API functions.
https://docs.blender.org/api/blender2.8/bpy.types.CollectionObjects.html

2 Likes

thank you, for the fast answer. This works great :see_no_evil::hear_no_evil::speak_no_evil:

hmmm…sorry to bother again. I guess my limited python is in my way, but I could only figure out half of the clue

I see that I better use code like this to move objects reliably to a specific collection (if thats what you meant):
bpy.data.colllections[“CollectionName”].objects.link(bpy.data.objects[Objectname])

However, I could not figure out how to create, remove, move and instance collections.
I could only find these operators:

bpy.ops.collection.create(name=“Collection”) … which creates a collection with the given name, which i can find by data.collections[’’]. but it doesn’t appear in the outliner.

yes the dirty one makes collections, too, but with the problems mentioned above
bpy.ops.object.move_to_collection(collection_index=n)

bpy.data.collections.remove(bpy.data.collections[‘CollName’]) removes the collection from bpy.data.collections-list. But than blender crashes when I hover over the outliner… I guess I delete from the wrong spot and its not updated…???

moving and instancing is even more a riddle to me.

Could you give me another hint how to approach these things?

thx in advance

Some examples:

# Create new collection
collection = bpy.data.collections.new(name="MyCollection")

# Add collection to scene
scene.collection.children.link(collection)

# Create collection instance in scene
object = bpy.data.objects.new(name="MyObject", object_data=None)
object.instance_collection = collection
scene.collection.objects.link(object)
3 Likes