I've created a mesh I want to duplicate using python with specifications for the new duplicate's coordinates. How do I do that?
3 Answers
You can simply use Object Duplicate Operator on the selected object(s) in Object Mode:
bpy.ops.object.duplicate()
By default this will create an identical copy, like pressing Shift+D in 3d View. By passing linked=True
to the operator, you can also create a linked duplicate like pressing Alt+D on the keyboard. This will create a new object with all of its data (like the mesh) linked to the original object.
To adjust the location, access the Active Object (which is the duplicate in this case) and simply overwrite the location values:
bpy.context.object.location = (x, y, z)
When duplicating multiple objects use bpy.context.selected_objects
to get a list of the created duplicates afterwards. Iterate through the list and assign new position values to each object.
For more options, see this question: Python move object on local axis
-
3$\begingroup$ You shouldn't use operators like this one in a loop however, or even avoid them whenever possible: blender.stackexchange.com/questions/7358/… $\endgroup$– CodeManXCommented May 25, 2015 at 17:37
You can create a copy of the Mesh datablock, create a new Object, position it where ever you want and attach it to the current collection/scene like this:
Blender 2.8x
import bpy
C = bpy.context
me = C.object.data # use current object's data
me_copy = me.copy()
ob = bpy.data.objects.new("Mesh Copy", me_copy)
ob.location = (1,2,3)
# Link object to the collection in context
C.collection.objects.link(ob)
# Update the view layer
C.view_layer.update()
Blender 2.7x
import bpy
me = bpy.context.object.data # use current object's data
me_copy = me.copy()
ob = bpy.data.objects.new("Mesh Copy", me_copy)
ob.location = (1,2,3)
scene = bpy.context.scene
scene.objects.link(ob)
scene.update()
You may also duplicate the original object. If you set the new object's data
attribute to the original mesh datablock (no mesh copy created), it will be a linked duplicate.
Here's how you can duplicate an object starting from Blender 2.8x:
import bpy
targetObject = bpy.data.objects['TargetObjectName']
# Or you can get the target object in other ways, such as:
# targetObject = bpy.context.active_object
newObject = targetObject.copy()
newObject.data = targetObject.data.copy() # Omit if you want a linked object.
bpy.context.collection.objects.link(newObject)