0
$\begingroup$

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)
$\endgroup$
4
  • 3
    $\begingroup$ What's your question? Cycles, BI or Eevee? BTW: Alternatively have a look into vertex colors: blender.stackexchange.com/questions/909/… $\endgroup$
    – brockmann
    Jun 24 '19 at 8:27
  • 1
    $\begingroup$ Vertices don't have material data, the material is assigned to faces. bpy.context.object.data.polygons[0].material_index $\endgroup$
    – sambler
    Jun 24 '19 at 8:49
  • $\begingroup$ 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. $\endgroup$ Jun 24 '19 at 9:43
  • $\begingroup$ @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. $\endgroup$ Jun 24 '19 at 16:03
1
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.