I wrote this script to put vertexes and their colors into a JSON file for a project I'm working on. I was using this answer to get the colors. Here's the script that I wrote with that.
import bpy
import json
ob = bpy.context.active_object
me = ob.data
#check for edit mode
editmode = False
if ob.mode == 'EDIT':
editmode =True
#the following sets mode to object by default
bpy.ops.object.mode_set()
j = {
"name": "Fish",
"mesh": []
}
verts = [ bpy.context.object.matrix_world @ v.co for v in bpy.context.object.data.vertices ]
color_layer = me.vertex_colors["Col"]
my_object = bpy.context.active_object.data
vert_list = my_object.vertices
color_map = my_object.vertex_colors.new()
# Get the active vertex color layer
color_data = me.vertex_colors.active.data
size = 15
i = 0
for poly in my_object.polygons:
if poly.select:
p = []
r = []
g = []
b = []
a = []
for idx in poly.loop_indices:
loop = my_object.loops[idx]
v = loop.vertex_index
x = vert_list[v].co.x * size
y = vert_list[v].co.y * size
z = vert_list[v].co.z * size
p.append([y, z, x])
r.append(color_map.data[i].color[0])
g.append(color_map.data[i].color[1])
b.append(color_map.data[i].color[2])
a.append(color_map.data[i].color[3])
i += 1
tri = {
"p0": [p[0][0], p[0][1], p[0][2]], # y and z are
"p1": [p[1][0], p[1][1], p[1][2]], # switched in
"p2": [p[2][0], p[2][1], p[2][2]], # my game
"color": {
"r": sum(r)/len(r) * 255,
"g": sum(g)/len(g) * 255,
"b": sum(b)/len(b) * 255,
"a": sum(a)/len(a) * 255
}
}
j["mesh"].append(tri)
#for index in range(len(p.vertices)): # for each vertex in triangle 0, 1, 2
#print(verts[p.vertices[index]]) # prints each vertex in triangle
#obj = json.loads(str(j))
json_formatted_str = json.dumps(j, indent=4)
try:
f = open("F:/Leviathan/points.txt", "w")
f.write(json_formatted_str)
f.close()
except:
pass
#done editing, restore edit mode if needed
if editmode:
bpy.ops.object.mode_set(mode = 'EDIT')
It worked great until it didn't. I'm not sure what I did but i get an error at r.append(color_map.data[i].color[0])
where it says AttributeError: 'NoneType' has no attribute 'data'
. If I make a new project, paint the object, and copy the script, it works fine. I used it for a few minutes before i got the error. Any help is appreciated
my_object
i getMesh("Cube")
and so I'm not quite sure thats the issue... If it is the issue, how should i fix it? $\endgroup$r.append(color_map.data[i].color[0])
tor.append(color_map.elements[i].color[0])
$\endgroup$color_map
. $\endgroup$AttributeError: 'NoneType' has no attribute 'elements'
$\endgroup$