I'm trying to add some items to the scene and rename them but ran into some issues. Example code:

import bpy
context = bpy.context
name = "Cube"

bpy.ops.mesh.primitive_cube_add(location = [1,2,3])
item = context.active_object
item.name = name

bpy.ops.mesh.primitive_cube_add(location = [10,20,30])
item = context.active_object
item.name = name

I thought that this code would name the first cube to "Cube" and the second cube to Cube.001, but it actually does the opposite and I end up with the second cube (10,20,30) named Cube and the first is named Cube.001. Is this a bug?

Is there anyway around this other than manually looping over existing objects and generating a unique name?

I would be happy to use bmesh instead (as that will give me the expected behaviour), but I can't get that method to work either as I need to create a uv map as well. Example workaround:

import bpy
import bmesh

bm = bmesh.new()    
bmesh.ops.create_cube(bm, size=1.0, calc_uvs=True)
mesh_name = "Cube"
mesh_data = bpy.data.meshes.new(mesh_name)

mesh_obj = bpy.data.objects.new(mesh_data.name, mesh_data)

With this example the naming is correct, but I have no uv maps.

Any suggestions?

  • 1
    $\begingroup$ This is not a bug. Same behavior using the UI. When you assign a name, Blender do what you want (so the second cube is named "Cube"), but as all names are unique, the other ones are renamed in consequence.You can manage that in your code, generating the wanted names by yourself. $\endgroup$
    – lemon
    Sep 29, 2020 at 14:40
  • $\begingroup$ I see. But in order to know a unique name (like Cube.001) I would need to loop over all objects in the scene first. Right? Seems like that would be a bit slow if you have thousands of objects in the scene? $\endgroup$ Sep 29, 2020 at 14:42
  • 1
    $\begingroup$ No. ` bpy.data.objects["name"]`is a map/dictionary. And you can test using "bpy.data.objects.get("name") $\endgroup$
    – lemon
    Sep 29, 2020 at 14:43
  • $\begingroup$ Ah perfect, works well. Thanks! $\endgroup$ Sep 30, 2020 at 13:18


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.