# Selecting a new material slot to selected vertices

I have a few vertices selected and would like to change the colour of those vertices with Python script. This means adding a new material slot.

I have tried this script, however it changes all the vertices and not the ones selected.

activeObject = bpy.context.active_object #Set active object to variable
mat = bpy.data.materials.new(name="MaterialName") #set new material to variable
activeObject.data.materials.append(mat) #add the material to the object
bpy.context.object.active_material.diffuse_color = (0.121583, 0.144091, 0.8, 1)

• What's your question? Cycles, BI or Eevee? BTW: Alternatively have a look into vertex colors: blender.stackexchange.com/questions/909/… Jun 24 '19 at 8:27
• Vertices don't have material data, the material is assigned to faces. bpy.context.object.data.polygons[0].material_index Jun 24 '19 at 8:49
• I meant faces not vertices. I would normally select the object, go into edit mode, then add plus to add a new material, then add new, change the colour, then asign, then exit edit mode. Jun 24 '19 at 9:43
• @MichaelTeiniker When posting programming or scripting answers properly formatting code is important for others to be able to help you. Whenever necessary use the builtin tools to properly format your posts. Jun 24 '19 at 16:03

One way to do this:

import bpy

mat = bpy.data.materials.new("PinkMaterial")
mat.diffuse_color=((0.8,0.2,0.8))
bpy.context.object.data.materials.append(mat)

for p in bpy.context.object.data.polygons:
if p.select:
p.material_index = len(bpy.context.object.material_slots)-1


This would add a pink material to the active object and then go through it's faces to see which ones are selected and then change their material index to the last one.

There might be more efficient ways to do this as well.