finding out if an object has a material

for a script i make i need to know if the active object has a material, and if it hasn’t, add a new one. would be logical, but i haven’t found a wat to know of wich opject wich material is.

if the object has a material:


# if no materials associated with it

# if it does have a material then it will display something like

so you can check if [] is returned, if it is… then there are no materials.

this returns a string and if the string isn’t empty the object has a material right?

experiment, it returns an empty list if no materials are associated

so you have an object with no materials, in console do this


the output will be <class ‘list’> , the class addition tells you the return type of items()

Or you could try:

obj =
if len( == 0:
    newMat ='newmaterial')

thanks :slight_smile:

another question:

i am making a new image, (‘normalmap.’, random), but now i have to assign it to the active object (using the way to do it with materials) does not work, and also the bpy.ops.uv seems not to have a solution.

how frustrating that all i need is 1 line of tokens put in the right order…

Hi flokkievids,

# Loads image from disk (1st line) or uses an image loaded (or generated) previously (2nd line).
myImg ='C:/path/to/the/image.jpg')
myImg =['image name.jpg'] 

# Sets the texture type to image
bpy.context.active_object.material_slots['Material'].material.texture_slots['Tex'].texture.type = 'IMAGE'
# Assigns the image to the texture
bpy.context.active_object.material_slots['Material'].material.texture_slots['Tex'].texture.image = myImg

That should do the trick :slight_smile:

alright, that should work, but i’m getting an error 'cause i got no type extension behind a newly made image. wich extension do they have on default? i tried png so far, and also that gave an error.

when putting
bpy.context.active_object.material_slots[‘Material’].material.texture_slots[‘Texture.001’].texture.type = ‘IMAGE’
in the console it’s alright, but in the script it says
‘MateriaSlot has no atribute texture_slots’, why does it work in the console, and not in my script…

Hi flokkievids,

I copied the exact code I posted, tested it on the default Blender scene and it worked perfectly when invoked from a script. The only change was I used the first line for myImg = … and I used a path to a real image in my hard disk drive.

I think the easiest way to get correct code is to leverage the autocompletion feature (Ctrl+Space) in the console.