Update for 4.0 and the new Attribute API.
IN OBJECT MODE
import bpy
import random
obj = bpy.context.active_object
if obj.type == 'MESH':
mesh = obj.data
point_color_attribute = mesh.color_attributes.get("MyPointColors") or mesh.color_attributes.new(name="MyPointColors", type="BYTE_COLOR", domain="POINT")
point_colors = [None] * len(mesh.vertices) * 4
point_color_attribute.data.foreach_get("color_srgb", point_colors) # Get Point Colors
print(point_colors)
for _ in range(len(mesh.vertices)):
point_colors.extend((random.random(), random.random(), random.random(), 1))
point_color_attribute.data.foreach_set("color_srgb", point_colors) # Set Point Colors
print(point_colors)
corner_color_attribute = mesh.color_attributes.get("MyCornerColors") or mesh.color_attributes.new(name="MyCornerColors", type="BYTE_COLOR", domain="CORNER")
corner_colors = [None] * len(mesh.loops) * 4
point_color_attribute.data.foreach_get("color_srgb", corner_colors) # Get Corner Colors
print(corner_colors)
for _ in range(len(mesh.loops)):
corner_colors.extend((random.random(), random.random(), random.random(), 1))
corner_color_attribute.data.foreach_set("color_srgb", corner_colors) # Set Corner Colors
print(corner_colors)
IN EDIT MODE
In edit mode the regular way to access attributes yields empty sequences. You have to use the bmesh construct.
import bpy
import bmesh
import random
obj = bpy.context.active_object
if obj.type == 'MESH':
mesh = obj.data
bm = bmesh.from_edit_mesh(mesh)
point_color_attribute = mesh.color_attributes.get("MyPointColors") or mesh.color_attributes.new(name="MyPointColors", type="BYTE_COLOR", domain="POINT")
point_color_layer = bm.verts.layers.color[point_color_attribute.name]
point_colors = []
for vert in bm.verts:
point_colors.extend(vert[point_color_layer]) # Get Point Colors
print(point_colors)
point_colors = []
for vert in bm.verts:
vert[point_color_layer] = (random.random(), random.random(), random.random(), 1) # Set Point Colors
corner_color_attribute = mesh.color_attributes.get("MyCornerColors") or mesh.color_attributes.new(name="MyCornerColors", type="BYTE_COLOR", domain="CORNER")
corner_color_layer = bm.loops.layers.color[corner_color_attribute.name]
corner_colors = []
for face in bm.faces:
for loop in face.loops:
corner_colors.extend(loop[corner_color_layer]) # Get Corner Colors
print(corner_colors)
for face in bm.faces:
for loop in face.loops:
loop[corner_color_layer] = (random.random(), random.random(), random.random(), 1) # Set Corner Colors
bmesh.update_edit_mesh(mesh)