1
$\begingroup$

I want to duplicate an object (by name). In this case, tried "Cube":

src_obj = bpy.data.objects["Cube"]
#print (src_obj) #ok, seems selected
new_obj = src_obj.ops.object.duplicate(linked=0,mode='TRANSLATION')

which gives me: 'Object' object has no attribute 'ops'

How can I fix it?

Thanks.

$\endgroup$
1

1 Answer 1

1
$\begingroup$

bpy.ops is a module directly in bpy, not part of any object class. It holds all registered operators. If you don't specify a region, it will always assume you want to do something in the viewport. Just replace src_obj with bpy to match the behavior of ShiftD. You should also make sure that the cube is the active object.

bpy.context.view_layer.objects.active = src_obj
scr_obj.select_set(True)
bpy.ops.object.duplicate(linked=0,mode='TRANSLATION')
new_obj = bpy.context.active_object
$\endgroup$
7
  • $\begingroup$ Thanks for the explanation, it makes sense. I can't use cube as the selected object, because it'll be cloned on the position of the actual selected object. Any workaround you would suggest? $\endgroup$
    – fran35
    Commented Oct 3, 2020 at 15:10
  • $\begingroup$ I'm not sure what you mean, you can move the new object to any location and you can store as many objects as you want in variables, or even easier just store the location in a Vector() $\endgroup$ Commented Oct 3, 2020 at 15:27
  • $\begingroup$ Some context, I'm using a loop to get object positions from a given collection (several collections, several types of objects to be duplicated and positioned). For each object in collection, I need to duplicate specific object type and place them in position of each object in collection. $\endgroup$
    – fran35
    Commented Oct 3, 2020 at 15:30
  • $\begingroup$ just pre-store them my_objects = [ob for ob in bpy.data.objects if ob pleases_me] Then you can call them at any point for ob in my_objects: $\endgroup$ Commented Oct 3, 2020 at 15:33
  • $\begingroup$ thanks, got it working, just had to deselect before changing my location. $\endgroup$
    – fran35
    Commented Oct 3, 2020 at 15:42

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