Page 1 of 1

object selection and duplication with python

Posted: Mon Oct 15, 2012 4:59 pm
by envif
I try to select an object and duplicate it with python, but I have some problems...

open the default blender project and type this code

Code: Select all

bpy.context.scene.objects.active=bpy.data.objects["Lamp"]
bpy.ops.object.duplicate_move()
the cube is dupplicated and not the Lamp...
I want to duplicate an object with python without selected it with the mouse.

Can someone give me help?
Thank's

Posted: Tue Oct 16, 2012 7:58 pm
by wretch1958
I think it is best to define selected object rather than active object.

Blender will take care of "active" object on its own. At any time, there is always supposed to be only one "active" object but can have several selected objects. If there is nothing selected, and you select "ob1" then "ob2", "ob2" is active object. If you then delete "ob2" then "ob1" (the last selected ob still in existence) is active etc... something like that, you get the idea. Sometimes active is not necessarily selected if you deselect all, there is still one active and active does not trigger selection to ON. I use:

Code: Select all

try:
	bpy.ops.object.mode_set(mode='OBJECT')
	bpy.ops.object.select_name(name=obj_name, extend=False)
except:
	print("Error selecting objects[" + obj_name + "]")
	print(" -- verify: change mode to OBJECT and/or object exists")
[/code]
The bpy.ops.object.select_name can have extend=True (your object added to already selected) or extend=False (everything deselected except your object)

Posted: Wed Oct 17, 2012 5:26 pm
by CoDEmanX
i'd rather use

ob = bpy.data.objects["Lamp"].copy()

and if you don't want the duplicated object to refer to same datablock, add:

ob.data = bpy.data.objects["Lamp"].data.copy()

Posted: Tue Oct 23, 2012 4:38 pm
by envif
Thanks a lot for your answers!