2
$\begingroup$

I'm trying to get and set the vertex colors of a mesh through a python script. However, the script seems unable to find the vertex color data, claiming the data set has length 0 despite that clearly not being the case.

import logging
logging.basicConfig(level=logging.DEBUG,format='(%(threadName)-10s) %(message)s',)

obj = bpy.context.edit_object

mesh = obj.data

if not mesh.vertex_colors:
    mesh.vertex_colors.new()
    logging.debug("Mesh had no vertex colors, adding them")

color_layer = mesh.vertex_colors.active

logging.debug(mesh)
logging.debug(mesh.vertex_colors)
logging.debug(len(color_layer.data))

if len(color_layer.data) > 0:
    i = 0
    for poly in mesh.polygons:
        for idx in poly.loop_indices:
            color_layer.data[i].color = (1.0, 0.0, 0.0)
            i += 1

This is the console output:

(MainThread) bpy_struct, Mesh("Cube")
(MainThread) bpy_collection1, LoopColors
(MainThread) 0


Here is my mesh, which very clearly has a non-zero list of vertex colors:
enter image description here
enter image description here

Anyone knows what's happening?

$\endgroup$
2
$\begingroup$

It seems that the way to go about it is, unintuitively, to exit edit mode into object mode in order to perform any vertex-level stuff, and then re-enter edit mode at the end of your script.


mode = bpy.context.active_object.mode
bpy.ops.object.mode_set(mode = 'OBJECT')

ob = bpy.context.active_object

for vcol in ob.data.vertex_colors:
#sample or do stuff to the vertex colors

bpy.ops.object.mode_set(mode=mode)

$\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.