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).
1 Answer
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)
-
2$\begingroup$ Instead of
if 1>len(obj.data.materials)
you can simply useif obj.data.materials
. $\endgroup$ 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$ Jan 23, 2018 at 15:13