Coloring a Mesh when creating it

Hello everyone,

I apologize if I word some things incorrectly, I am actually very new to scripting in Blender (Am more of an AI/Robotics programmer, but am using Blender for a project in my lab)

In any case, I am having trouble coloring a created Mesh. Here is the code I currently have for one of my functions:

def createPlane( x, y, z ):
### PLANE/FLOOR IMPLEMENTATION ###
#Define vertices, faces
verts = [(0,0,0),(x,0,0),(x,y,0),(0,y,0)]

# The number sequence refers to the vertex array items.
# The order will determine how the face is constructed.
faces = [(0,1,2,3)]
 
# Define mesh and object variables
mymesh = bpy.data.meshes.new("Plane")


#the mesh variable is then referenced by the object variable
myobject = bpy.data.objects.new("Plane", mymesh)  

myobject.color = (255,255,255,255) #Can't seem to get this to work
 
#Set location and scene of object
myobject.location = [0, 0, z]
bpy.context.scene.objects.link(myobject)
 
#Create mesh
#this method has an optional 'edge' array input. This is left as an empty array
mymesh.from_pydata(verts,[],faces)
mymesh.update(calc_edges=True)

I know that objects have object.color, and I figured that would allow me to add color to my plane, but it is not working.

I am able to add color manually by using Diffuse Color in Editor Type > Material > Diffuse, but is there a way to do this during my script? The worlds I am building get particularly big so I would rather do this automatically.

I am sorry since I have seen threads that have asked similar questions before but none of them seemed to piece together what I needed in order to do this in my script.

I don’t know what the object.color is for, but you can use materials to add color:

import bpy

verts = [(0,0,0),(1,0,0),(1,1,0),(0,1,0)]
faces = [(0,1,2,3)]
mymesh = bpy.data.meshes.new("Plane_mesh")
mymesh.from_pydata(verts,[],faces)
myobject = bpy.data.objects.new("Plane",mymesh)
myobject.location = [0,0,0]
bpy.context.scene.objects.link(myobject)

mymat = bpy.data.materials.new("Plane_mat")
mymat.diffuse_color = ( 1.0, 0.0, 0.0 )
mymesh.materials.append(mymat)

That should give you a red plane.

If you want transparency (alpha), add this:

mymat.alpha = 0.2
mymat.use_transparency = True
myobject.show_transparent = True

I hope i can be a little usefull here:

Try to use


myobject.color = [1.0, 1.0, 1.0, 1]

instead of

myobject.color = (1.0, 1.0, 1.0, 1)

I know it works in the BGE like this, where: [R,G,B,Alpha]
Every color portion has to be in the range of 0 - 1.
Hope it can be used here.