How do I select a material?

I making a script that iterates through all of the selected objects, selects verts by the material and does a quick uv unwrap. I’m having trouble selecting the material slot though.

import bpy

for i in bpy.context.selected_objects:
    
    
    bpy.ops.object.editmode_toggle()
    
    #assign all selected scene objects to context
    bpy.context.scene.objects.active = i
    
    
    bpy.ops.mesh.select_all(action = 'DESELECT')
    
    #need to assign the active material to slot 1
    #????
    
    
    bpy.ops.object.material_slot_select()
    
    bpy.ops.uv.unwrap(method = 'ANGLE_BASED')
    
    bpy.ops.object.editmode_toggle()[

Hi,

You can set them with mesh.active_material and mesh.active_material_slot

To set the active material to slot 0 to the active material



mat = mesh.active_material
mesh.active_material_index = 0
mesh.active_material = mat

Using mesh.active_material = mat … effectively gives you mesh.material_slots[mesh.active_material_index].material = mat

mesh is a mesh object akin to below.



# list all the materials for selected mesh objects.
import bpy


context = bpy.context


mesh_objs = [ob for ob in context.selected_objects if ob.type == 'MESH']


for mesh in mesh_objs:
    
    print(repr(mesh))


    print("active_slot:", mesh.active_material_index)
    if mesh.active_material is not None:
        print("active_material:", mesh.active_material.name)
        
    for i, mat in enumerate(mesh.material_slots):
        if not i:
            print("material_slots")
        if mat is not None:
            print("	[%d] = %s" % (i, mat.name))
        else:
            print("	[%d] is None" % i)
            
    print()
            
        


Thanks for the help, that’s exactly what I needed.

import bpy

for i in bpy.context.selected_objects:
    
    
    bpy.ops.object.editmode_toggle()
    
    #assign all selected scene objects to context
    bpy.context.scene.objects.active = i
    
    
    bpy.ops.mesh.select_all(action = 'DESELECT')
    
    #assign the active material to slot 1
    i.active_material_index = 1
    
    
    bpy.ops.object.material_slot_select()
    
    #bpy.ops.uv.unwrap(method = 'ANGLE_BASED')
    bpy.ops.uv.cube_project()
    
    
    i.active_material_index = 0
    bpy.ops.object.editmode_toggle()