Python - Set material to material slot

I am using the Blender Internal render engine. I have an material slot with no material assigned to it:


I need some python code to be able to:

  • work in edit mode
  • work when I want to assign random faces a material in edit mode
  • specify the material that is assigned

So, basically, I need to go into edit mode via python, select random faces and assign a material.

I’ve tried:

bpy.context.object.active_material_index = 0
bpy.ops.object.material_slot_assign()

but that won’t let me specify the material that is assigned.

I’ve also tried:

import bpy
D = bpy.data
if len(D.objects[‘Cube’].material_slots) < 1:# if there is no slot then we append to create the slot and assign
D.objects[‘Cube’].data.materials.append(D.materials[‘Material’])
else:# we always want the material in slot[0]
D.objects[‘Cube’].material_slots[0].material = D.materials[‘Material’]

but this doesn’t work when I want to assign random faces a material in edit mode.

Any ideas?

Thanks!

(sorry for the poorly formatted code, for some reason my browser is acting up or something)

:stuck_out_tongue:

Abandon the approach of edit mode/non-edit mode and just focus on the datablock. Materials for faces are specified via material_index inside the datablock of a mesh type object.

Add a Suzanne mesh to the scene and try this code.


import bpy, random

ob = bpy.data.objects.get("Suzanne")
if ob != None:
    # Create materials.
    mat_one = bpy.data.materials.get("mat_one")
    if mat_one == None:
        mat_one = bpy.data.materials.new("mat_one")
    mat_one.diffuse_color = (random.random(),random.random(),random.random())

    mat_two = bpy.data.materials.get("mat_two")
    if mat_two == None:
        mat_two = bpy.data.materials.new("mat_two")
    mat_two.diffuse_color = (random.random(),random.random(),random.random())
    
     # Add materials to slots.       
    if len(ob.material_slots) != 2:     
        ob.data.materials.append(mat_one)
        ob.data.materials.append(mat_two)  
    
    # Determine random count and poly count.  
    rnd_face_count = 12
    l = len(ob.data.polygons)
    
    # Note: By default all faces have a material index of 0.
    for i in range(rnd_face_count):
        # Generate a random face index.
        rnd_face_index = random.randint(0,(l-1))
        ob.data.polygons[rnd_face_index].material_index = 1


Note: There is no real checking to make sure that the new random number has not already been generated once before. So if you end up with less than your random count it probably is because the same material _index number was generated twice.

Thanks Atom, I’ll try it!
:slight_smile: