Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save openroomxyz/5493e021ab7729a1f6d33ca2ee7c5106 to your computer and use it in GitHub Desktop.
Save openroomxyz/5493e021ab7729a1f6d33ca2ee7c5106 to your computer and use it in GitHub Desktop.
Python : How to move an object from once collection to another, if collection does not exist create it?
import bpy
import uuid
##
def find_collection(context, item):
collections = item.users_collection
if len(collections) > 0:
return collections[0]
return context.scene.collection
def make_collection_if_does_not_exist(collection_name, parent_collection):
if collection_name in bpy.data.collections: # Does the collection already exist?
return bpy.data.collections[collection_name]
else:
new_collection = bpy.data.collections.new(collection_name)
parent_collection.children.link(new_collection) # Add the new collection under a parent
return new_collection
def move_object_with_name_into_collection(name_of_object, name_of_connection_we_are_moving_the_object):
# Step 1
cube = bpy.data.objects[name_of_object]
cube_collection = find_collection(bpy.context, cube)
new_collection = make_collection_if_does_not_exist(name_of_connection_we_are_moving_the_object, cube_collection)
# Step 2
new_collection.objects.link(cube) # put the cube in the new collection
cube_collection.objects.unlink(cube) # remove it from the old collection
move_object_with_name_into_collection("Generated", "GEN")
move_object_with_name_into_collection(n1, "GEN")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment