1

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
        bpy.ops.object.material_slot_add()
    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 :)

ValiGrimO
  • 77
  • 6

1 Answers1

2

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
bpy.data.objects['Cube'].material_slots

>>> len(C.object.material_slots) 4

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 else: # In case there is no material, append the Demo material obj.data.materials.append(mat)

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

brockmann
  • 12,613
  • 4
  • 50
  • 93