RE:selecting similar objects with python


(djphotoduck) #1

I was wondering if there is a way to use python to do the following:

-select all objects with names that start the same (same letter, or object type, for example select all spheres, or all objects with names that start with ‘C’, etc)

-assign a new material to all the selected objects

By the way, I’m not a programmer, but I can digest code pretty well if shown the way.

Thanks,
Dan


(eeshlo) #2

If you use Publisher then yes to both, if not, then only yes to the first.

To get a list of objects that have names starting with the letter ‘C’:


import Blender
C_objects = [ob for ob in Blender.Object.Get() if ob.name[0]=='C']

Or this which is the longer version, but does the same:


import Blender
C_objects = []
for ob in Blender.Get.Objects():
    if ob.name[0]=='C': C_objects.append(ob)

You can only assign materials in 2.25, you can assign materials to meshes or to objects. You can sort of do this in 2.23 but it is not worth the trouble.


import Blender
ob = Blender.Object.get(name)
# create a new material as an example
mt = Blender.Material.New('example_mat')
# assign the material to the object
# the argument must be a list, even if it is only one material
ob.setMaterials([mt])

You can assign it to the mesh, using two methods, you can add an extra line to the code above:


ob.setMaterialUsage('Data')

Which means that the materials are assigned to the object data instead of the object itself.
But you can also assign it directly to the mesh like this:


import Blender
ob = Blender.Object.get(name)
me = ob.getData()
# create a new material as an example
mt = Blender.Material.New('example_mat')
# assign the material to the mesh
me.setMaterials([mt])


(djphotoduck) #3

Thank you. I will give that a try.

Dan