Apply operation on all objects in collection - python

Hi,

I have a collection with parts. And I want to replace the mesh data of each object. For that, I use the name of the object and remove the last four characters. (.001, .002, etc).

I made a code, and that works, but only works on the active mesh:

import bpy
for obj in bpy.data.collections[‘Assets’].all_objects:
bpy.context.object.data.name = bpy.context.object.name[:-4]

What I need is that all the objects need to have it’s mesh data replaced, and not one object from the collection. In other words, how to iterate through a collection and apply operation on all objects within a collection?

what you can try to do instead of using context, is using data:

for obj in myCollection:
  name = obj.name
  bpy.data.objects[name].name = name[:-4]

The other methode is to change the active object when iterating:

for obj in myCollection:
  bpy.context.view_layer.objects.active = obj
  bpy.context.object.data.name =  bpy.context.object.data.name[:-4]

It seems there is also an operator bpy.ops.object.rename_object but i have no clue on the utilization

Thanks, a step further now.
I tried it on a collection with 6 objects. The only strange thing is that only four of them got their mesh data replaced. Note that I take the object.name, remove 4 characters and use that for object.data.name
I will test again, and see why not all mesh data got replaced.

import bpy
myCollection = bpy.data.collections[‘Assets’].all_objects
for obj in myCollection:
bpy.context.view_layer.objects.active = obj
bpy.context.object.data.name = bpy.context.object.name[:-4]

update: awh, I am also renaming the mesh data, I should replace it like:
bpy.context.object.data = bpy.data.meshes[‘Plane.050’]

Yes!

So got it working:

> import bpy
> myCollection = bpy.data.collections['Assets'].all_objects
> for obj in myCollection:
>     bpy.context.view_layer.objects.active = obj
>     a = bpy.context.object.name[:-4]
>     bpy.context.object.data = bpy.data.meshes[a]
1 Like

It’s my fault, i made a small mistake.
It should be:

for obj in myCollection:
  bpy.context.view_layer.objects.active = obj

  #Renames object itself
  bpy.context.object.name =  bpy.context.object.name[:-4]
  #Renames object data (mesh, curve and stuff)
  bpy.context.object.data.name =  bpy.context.object.data.name[:-4]
1 Like