# 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)


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.