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. bpy.data would be logical, but i haven’t found a wat to know of wich opject wich material is.
if the object has a material:
>>> bpy.context.active_object.data.materials.items() # if no materials associated with it  # if it does have a material then it will display something like [('Material', bpy.data.materials["Material"])]
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 = bpy.context.scene.objects.active if len(obj.data.materials) == 0: newMat = bpy.data.materials.new('newmaterial') obj.data.materials.append(newMat)
i am making a new image, (‘normalmap.’, random), but now i have to assign it to the active object
bpy.context.scene.objects.active.data.images.append(normalmap.007) (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…
# Loads image from disk (1st line) or uses an image loaded (or generated) previously (2nd line). myImg = bpy.data.images.load('C:/path/to/the/image.jpg') myImg = bpy.data.images['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
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.
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…
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.