Set vertex color

24 Ⅷ 2013

When using BMesh, you get at the Vertex Colors the same way as Creases, or Vertex Groups. It is all part of the Customdata Layers. This is a small script that loops through all faces and makes those that are selected, bright red.

import bpy, bmesh

# A bright red color (RGB)
red = [1.0, 0.0, 0.0]

# The name of the vertex color layer I want to use
layer_name = 'redLayer'

ob = bpy.context.active_object
me = ob.data

# Let's get the bmesh data
# This method is for object mode only!
bm = bmesh.new()
bm.from_mesh(me)

# Get the color custom data layer or make one if it doesn't exist!
'''
Remember that this is not the actual vertex colors as with the old api! ALSO... vertex colors are done per face... and this means you use bm.loops, not bm.verts. bm.loops holds all the information for the verts that is kept "per face".
'''
try:
	color_layer = bm.loops.layers.color[layer_name]
except:
	color_layer = bm.loops.layers.color.new(layer_name)
	
'''
# If you do not want to use a layer defined by name but the currently active one you can do the following:
color_layer = bm.loops.layers.color.active
if color_layer is None: color_layer = bm.loops.layers.color.new()
'''

# Loop through all faces, and for every selected face through it's loops (vertex data specific to that face)
for f in bm.faces:
	if f.select:
		for L in f.loops:
			L[color_layer] = red

# That's it... we're done... so we put the bmesh back in the object
bm.to_mesh(me)
bm.free()