2
$\begingroup$

I want to create a script that check if the mesh has a material, if not it applies a diffuse shader with mid grey (value 0.735).

$\endgroup$
2
  • 2
    $\begingroup$ What haver you tried, where is your script going wrong? $\endgroup$ Jul 23, 2017 at 17:35
  • $\begingroup$ I don't know the command line to do that. $\endgroup$ Jul 23, 2017 at 17:36

1 Answer 1

1
$\begingroup$

If the mesh has no materials then

1>len(obj.data.materials)

although it is also possible that it has a material slot with nothing in it

obj.data.materials[i] is None

and the complete script is

import bpy

def no_material_on(mesh):
    if 1>len(mesh.materials):
        return True

    for i in range(len(mesh.materials)):
        if mesh.materials[i] is not None:
            return False
    return True

def my_grey():
    name = "my grey"
    rval = bpy.data.materials.get(name)
    if rval is None:
        rval = bpy.data.materials.new(name)
        g=.735
        rval.diffuse_color = (g,g,g)
    return rval


def mission1(obj):
    mesh = obj.data
    if no_material_on(mesh):
        mat = my_grey()
        if 1>len(mesh.materials):
            mesh.materials.append(mat)
        else:
            mesh.materials[0] = mat

#

mission1(bpy.context.active_object)
$\endgroup$
2
  • 2
    $\begingroup$ Instead of if 1>len(obj.data.materials) you can simply use if obj.data.materials. $\endgroup$
    – dr. Sybren
    Dec 17, 2017 at 1:15
  • 1
    $\begingroup$ len([s for s in C.object.material_slots if s.material]) will work for any object type. $\endgroup$
    – batFINGER
    Jan 23, 2018 at 15:13

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.