How can I get a reference to the object created by bpy.ops.object.duplicate()
? It seems that bpy.context.object
used to have it, but not anymore.
2 Answers
bpy.ops.object.duplicate()
finishes with the duplicated object as the currently selected object. Therefore, bpy.context.object
is the reference to the new object.
Ex (assume object selected in 3d viewport):
import bpy
bpy.ops.object.duplicate()
dupli_obj = bpy.context.object
print(dupli_obj.name) #check the console
If you run this code, does it not give you what you expect?
-
$\begingroup$ I tried your script in a brand new file. It returned the original Cube, not Cube.001 that was created. I know it's weird, but that's what happens, at least in v2.81.16. $\endgroup$ Feb 14, 2020 at 0:49
-
$\begingroup$ That's what I'm running as well and it behaves just as I explained. No idea why it isn't working for you. $\endgroup$ Feb 14, 2020 at 1:11
-
$\begingroup$ Works for me too 2.83.2. Worth mentioning it will dupe all selected objects. $\endgroup$ Feb 14, 2020 at 12:01
Try bpy.context.active_object
, works for me else try bpy.context.selected_objects[0]