Add material to geometry in script?

I’ve been using the script output window to get the function calls to write the scripts I need. But when I apply a material, that function call doesn’t get listed. How do I apply a material using a script?

Thanks!

Here’s how to either create a new one and apply or use the name of an existing one…


import bpy


def makeMaterial(name, diffuse, specular, alpha):
    mat = bpy.data.materials.new(name)
    mat.diffuse_color = diffuse
    mat.diffuse_shader = 'LAMBERT' 
    mat.diffuse_intensity = 1.0 
    mat.specular_color = specular
    mat.specular_shader = 'COOKTORR'
    mat.specular_intensity = 0.5
    mat.alpha = alpha
    mat.ambient = 1
    return mat

red = makeMaterial('Red', (1,0,0), (1,1,1), 1)
bpy.ops.mesh.primitive_ico_sphere_add(size = 1.0,location=(0,0,0))
ob = bpy.context.object
ob.data.materials.append(red)



mat_name="my_mat" # NAME OF EXISTING MATERIAL

bpy.ops.mesh.primitive_ico_sphere_add(size = 1.0,location=(2,0,0))
ob = bpy.context.object
ob.data.materials.append(bpy.data.materials[mat_name])

That works beautifully, thank you!