# How to add a color to a generated cube within a python script

I have tried several suggestions to create a cube and then apply color to it in a Python script. One such way is describe in Random object color via python . I am currently using python 2.9. Essentially what I have is as follows:

import bpy obj = bpy.ops.mesh.primitive_cube_add() obj.color = (0,0,1,1)

I was trying to create a blue cube. The system console states that there is no attribute for color. This must be an old syntax but I am not able to find the appropriate syntax to perform this basic task.

I also tried to simply cut and paste the bpy statements as I executed them manually but that didn't work either.

Any suggestions would be very much appreciated. Thank you,

Objects still have a color (as indicated in the documentation).

Though, bpy.ops does not return what is created or done by the ops, but the result state of the operation.

if you print(obj)in your code, you should see {'FINISHED'}.

What you can do using ops is:

import bpy

obj = bpy.context.object
obj.color = (0,0,1,1)


Because the operation links the object to the context.

So, this work, but the color won't be rendered except in workbench rendering. It is also visible in solid view when object is selected here:

To set this color to the material, you can complete the script by the following:

import bpy

obj = bpy.context.object

obj.color = (0,0,1,1)

# Create a material
mat = bpy.data.materials.new("Blue")

# Activate its nodes
mat.use_nodes = True

# Get the principled BSDF (created by default)
principled = mat.node_tree.nodes['Principled BSDF']

# Assign the color
principled.inputs['Base Color'].default_value = (0,0,1,1)

# Assign the material to the object
obj.data.materials.append(mat)

• Thanks lemon! This is exactly what I was looking for. I appreciate your prompt reply and the details describing the answer. Nov 14 '20 at 15:20
• Hi @SteveK If this is exactly what you were looking for, please consider to accept the answer. How this site works: blender.stackexchange.com/tour Nov 14 '20 at 19:31
• Hello @brockmann, I'm not in begging for RP, but yes you're right this is good for BSE and filtering approved answer. So thanks for your work. (have noticed this is not the first time) Nov 14 '20 at 19:36