Error in old code snippet bl 3.2




import bpy

mesh = bpy.data.meshes.new("myBeautifulMesh")  # add the new mesh
obj = bpy.data.objects.new(mesh.name, mesh)
col = bpy.data.collections.get("Collection")
col.objects.link(obj)
bpy.context.view_layer.objects.active = obj

when i run this in bl 3.2 i get an error on the line 20
line = col.objects.link(obj)

AttributeError: ‘NoneType’ object has no attribute ‘objects’

how to correct this to it works in bl 3.2

thanks for any feedback
happy bl

You need to have a collection in your scene named “Collection” for this code to work. Other than that, this should work fine in 3.2 :slight_smile:

i got one but was not activated
i set it on and still get same error

here whole code

import bpy

mesh = bpy.data.meshes.new("myBeautifulMesh")  # add the new mesh
obj = bpy.data.objects.new(mesh.name, mesh)
col = bpy.data.collections.get("Collection")
col.objects.link(obj)
bpy.context.view_layer.objects.active = obj

verts = [( 1.0,  1.0,  0.0), 
         ( 1.0, -1.0,  0.0),
         (-1.0, -1.0,  0.0),
         (-1.0,  1.0,  0.0),
         ]  # 4 verts made with XYZ coords
edges = []
faces = [[0, 1, 2, 3]]

mesh.from_pydata(verts, edges, faces)



###

import bpy
import bmesh

verts = [(1, 1, 1), (0, 0, 0)]  # 2 verts made with XYZ coords
mesh = bpy.data.meshes.new("mesh")  # add a new mesh
obj = bpy.data.objects.new("MyObject", mesh)  # add a new object using the mesh

scene = bpy.context.scene
scene.objects.link(obj)  # put the object into the scene (link)
scene.objects.active = obj  # set as the active object in the scene
obj.select = True  # select object

mesh = bpy.context.object.data
bm = bmesh.new()

for v in verts:
    bm.verts.new(v)  # add a new vert

# make the bmesh the object's mesh
bm.to_mesh(mesh)  
bm.free()  # always do this when finished



#####

thanks

replace line with
bpy.context.scene.collection.objects.link(obj)

this seem to work
but is it the right way ?

also corrected another line at 50
bpy.context.view_layer.objects.active = obj

thanks
happy bl

If it works, it works, I guess :sweat_smile: