14
$\begingroup$

In Python 2.8, I would like to create copies of the object 'CubeTemplate' but am having no luck. I have reviewed every blender.stackexchange post on this subject (this, this, this and this) but cannot get them to work - either they don't apply or the sample code throws errors (perhaps because it was pre 2.8).

The code below throws this error:

AttributeError: 'bpy_prop_collection' object has no attribute 'link'

for x in range(1, 3):
    bpy.data.objects['CubeTemplate'].select_set(True)
    bpy.context.view_layer.objects.active = bpy.data.objects['CubeTemplate']
    me = bpy.context.object.data # use current object's data
    me_copy = me.copy()
    ob = bpy.data.objects.new('CubeCopy'+str(x), me_copy)
    ob.location = (0, 0, x)
    scene = bpy.context.scene
    scene.objects.link(ob)
    scene.update()
$\endgroup$
0

2 Answers 2

25
$\begingroup$

The issue with your code comes from an api change in 2.80. We no longer link objects to the scene, they have to be linked to a collection.

So all you have to do to make your script work is to change your scene references to collections

You old code:

scene = bpy.context.scene
scene.objects.link(ob)
scene.update()

Replace with this:

scene = bpy.context.scene
scene.collection.objects.link(ob)

Or shorter:

bpy.context.collection.objects.link(ob)

Or if you wanted to link the objects to a specific collection you'd do this with this line:

bpy.data.collections["Collection Name"].objects.link(ob)
$\endgroup$
1
  • $\begingroup$ Is there a way to do this in Blender 2.79? $\endgroup$
    – rzaratx
    Commented Apr 7, 2020 at 21:13
1
$\begingroup$

This should work in 2.8:

import bpy
templateName = 'CubeTemplate'
template = bpy.data.objects[templateName]

for x in range(1, 3):
    template.select_set(True)
    bpy.ops.object.duplicate_move(TRANSFORM_OT_translate={"value":(x, 0, 0)})
    copy = bpy.data.objects[templateName + '.001']
    copy.name = 'CubeCopy' + str(x)

    bpy.ops.object.select_all(action='DESELECT')
$\endgroup$
2
  • 1
    $\begingroup$ DVed because it is better not to use ops. Plus it is just not needed for something simple like duplicating an object $\endgroup$
    – David
    Commented Jul 18, 2019 at 12:53
  • 1
    $\begingroup$ Thanks for the tip. I assume that using ops is not so great because of some overhead/performance consideration? It is the more easily learned route to accomplishing duplication since it's what prints in the Info window when manually performing the duplication. $\endgroup$ Commented Jul 18, 2019 at 18:24

You must log in to answer this question.

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