0
$\begingroup$

After loading a mesh into Blender, I want to apply a material on them and color it. I am doing this using the code below:

for ob in bpy.context.selectable_objects:
    #if ob.name.startswith('simplified_model'):
    if ob.type == 'MESH':
        obj = ob            # this is for scoping reasons
        obj.select = True
        self.scene.objects.active = obj
bpy.ops.object.select_all(action='SELECT')

self.model = obj

mat = bpy.data.materials.new('colored')
color = [0., 191./255, 255./255]
mat.diffuse_color = color
mat.specular_intensity = 0.3
self.model.active_material = mat

Using the code above, some of the meshes are colored the way I expect, but as you can see below most of them are painted incompletely and the material has not been applied the way it was expected to:

enter image description here

The meshes are expected to be colored as follow:

enter image description here

Can anyone tell me what I'm doing wrong?

Thank you

$\endgroup$
1
$\begingroup$

Programming languages are very literal and do exactly as they are written in the order that they are written, with python the formatting (line indentation) also makes a difference.

Assuming the code you show was pasted with the same formatting as the script you are running, you start by looping over every object and selecting it and making it active. bpy.ops.object.select_all(action='SELECT') will get the same result.

When the loop is finished you deselect all objects, select one object, set self.model to the last object in the loop then create and assign a material to the one object.

You could indent the lines that make the material so that it becomes part of the loop so that you get a new material created for each object. Another approach is to create the material first and then assign the same material to each object in a loop.

mat = bpy.data.materials.new('colored')
mat.diffuse_color = [0., 191./255, 255./255]
mat.specular_intensity = 0.3

bpy.ops.object.select_all(action='SELECT')
for ob in bpy.context.selected_objects:
    if ob.type == 'MESH':
        ob.active_material = mat
$\endgroup$
  • $\begingroup$ Thanks for your answer but this still does not work. The thing is before I run the code posted above, I join all the meshes. Therefore, I have a single mesh in the scene but it's strange why the material is only applied some parts of the objects. $\endgroup$ – Amir Sep 20 '16 at 14:24
  • $\begingroup$ If each mesh has it's own material you will end up with multiple materials on the mesh when you join them - see how it is done here. To undo that, remove the duplicates so there is only one material on the final object. $\endgroup$ – sambler Sep 20 '16 at 14:44

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.