0
$\begingroup$

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,

$\endgroup$
1
$\begingroup$

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 

bpy.ops.mesh.primitive_cube_add() 
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:

enter image description here

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

import bpy 

bpy.ops.mesh.primitive_cube_add() 

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)
$\endgroup$
3
  • $\begingroup$ Thanks lemon! This is exactly what I was looking for. I appreciate your prompt reply and the details describing the answer. $\endgroup$
    – SteveK
    Nov 14 '20 at 15:20
  • 1
    $\begingroup$ 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 $\endgroup$
    – brockmann
    Nov 14 '20 at 19:31
  • $\begingroup$ 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) $\endgroup$
    – lemon
    Nov 14 '20 at 19:36

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.