I’m using this script to create a whole bunch of cubes and add them to a collection for easier management:
def set_cubes(objname): #objname must be a string! i.e. use quotes around it.
objVerts = bpy.data.objects[objname].data.vertices
bpy.data.collections.new(objname+'Cubes')
bpy.data.collections['Collection'].children.link(bpy.data.collections[objname+'Cubes'])
for i in range(0, len(objVerts)):
bpy.ops.mesh.primitive_cube_add(size=2, enter_editmode=False, align='WORLD', location=objVerts[i].co, scale=(1, 1, 1))
bpy.data.collections[objname+'Cubes'].objects.link(bpy.context.selected_objects[0])
It works dandy, but when I click the eye next to the collection to hide my cubes, they do not become hidden. Any advice?
the cubes are created in the active collection and linked to the newly created “objname+‘Cubes’” collection but never unlinked from the collection that was active prior to running the script.
import bpy
def set_cubes(objname): #objname must be a string! i.e. use quotes around it.
objVerts = bpy.data.objects[objname].data.vertices
my_coll = bpy.data.collections.new(objname+'Cubes')
# link the new collection try to avoid fixed names
bpy.context.view_layer.layer_collection.collection.children.link(my_coll)
for i in range(0, len(objVerts)):
bpy.ops.mesh.primitive_cube_add(location=objVerts[i].co, scale=(1, 1, 1))
# bpy.ops operators generally return the new object as active
bpy.data.collections[objname+'Cubes'].objects.link(bpy.context.object)
# unlink from active collection
bpy.context.view_layer.layer_collection.collection.objects.unlink(bpy.context.object)
set_cubes("Cube")