# Check if a mesh has a material in Python

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).

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

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)

• Instead of if 1>len(obj.data.materials) you can simply use if obj.data.materials. Dec 17 '17 at 1:15
• len([s for s in C.object.material_slots if s.material]) will work for any object type. Jan 23 '18 at 15:13