When we assign or change the name of an object in Blender, we work at the object level. However, all objects also have a data block – a pointer to the actual object data, which also have names. The name of the data block can be seen by clicking on the corner arrow to the left of the object name in the outliner.
Initially, when we’re creating a new object (adding it to the scene), the name of the data block is the same as the name of the object itself.
1 2 3 4 5 6 7 |
bpy.ops.mesh.primitive_cube_add() print(bpy.context.object.name) print(bpy.context.object.data.name) # Cube # Cube |
However, the name of the data block does not always correspond to the name of the object.
The most obvious way – when we rename an object, the name of its data block does not change.
The name of the data block may diverge from the name of the object, even when we are simply deleting and adding same objects. Let’s add a cube to the scene and delete it several times. Then, execute the above code again.
1 2 3 4 5 6 7 |
bpy.ops.mesh.primitive_cube_add() print(bpy.context.object.name) print(bpy.context.object.data.name) # Cube # Cube.005 |
The name of the data block is no longer equal to the name of the object, since the counter of the object name is reset, but the counter of the data blocks is not.
In general, in most cases in a working scene, most of the names of data blocks do not correspond to the names of the objects that refer to them. However, this is very easy to fix.
Since the data block name can be changed, we can write the simplest code that will loop through all the selected objects in the scene (for which we want to match the names of objects and data blocks), and change the name of the data block to the name of the object.
1 2 |
for obj in bpy.context.selected_objects: obj.data.name = obj.name |
By executing this code, we will match the names of the data blocks and scene objects for the entire selection at once.