I am working on a project with mesh created with photogrammetry (mainly). Once the mesh is imported, I would like to apply through scripts different materials before render them. But

  • Sometimes, I use meshes with vertex color as color data, and they don't have any material's slot and I can't apply directly a material
  • Sometimes, I use meshes with textures, and UV's are dispatched in several slots... so i need to fill every slot with a material

I would like to write something like this in Python:

for "material_slot" of selected object
    if there is no material_slot
    if there is only 1 slot and more
        do nothing

for every slot of selected object
    apply material "demoMat"

I am not fluent in Python grammar, and don't know how to write this. Here is the documentation I found about material_slot management...

Thank you for your help :)


1 Answer 1


You can use pythons built-in len() function on the Object.material_slots collection to determine whether there are any material slots assigned to the objects material already. Suggest use the python console to figure out:

>>> C.object.material_slots

>>> len(C.object.material_slots)

Following demo replaces all materials assigned to the given slots of the object in context (bpy.context.object) by a material called "DemoMat". In case there is no material slot present the script appends a dedicated slot and assigns "DemoMat" as well:

import bpy

C = bpy.context
obj = C.object

# Get the material
mat = bpy.data.materials.get("DemoMat")
if mat is None:
    # Create the material if not present
    mat = bpy.data.materials.new(name="DemoMat")

# Determine whether there are slots to work with
if len(obj.material_slots) > 0:
    # Assign the material to each slot 
    for c, slot in enumerate(obj.material_slots):
        obj.material_slots[c].material = mat
    # In case there is no material, append the Demo material

Related: How to assign a new material to an object in the scene from Python?

  • 1
    $\begingroup$ Thank you very much!!! It's working fine :) $\endgroup$
    – ValiGrimO
    Oct 11, 2021 at 17:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .