1

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.

fran35
  • 13
  • 3

1 Answers1

1

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
brockmann
  • 12,613
  • 4
  • 50
  • 93
Frederik Steinmetz
  • 2,879
  • 1
  • 8
  • 11
  • 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? – fran35 Oct 03 '20 at 15:10
  • 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() – Frederik Steinmetz Oct 03 '20 at 15:27
  • 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. – fran35 Oct 03 '20 at 15:30
  • 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: – Frederik Steinmetz Oct 03 '20 at 15:33
  • thanks, got it working, just had to deselect before changing my location. – fran35 Oct 03 '20 at 15:42
  • If you can try to avoid ops, bc. they are easy to mess up, depending on the environment (hidden objects, no VP open, wrong objects selected), try making it a habit to set loc/rot/scale rather than translating. src_obj.position = Vector((x,y,z)) – Frederik Steinmetz Oct 03 '20 at 16:03
  • Here you go: https://blender.stackexchange.com/a/31353/31447 – brockmann Oct 03 '20 at 17:24