0
$\begingroup$

In Blender/python 2.8, I have code that creates and assigns a material correctly in the Layout workspace (Workbench engine), but when I switch to Eevee or Cycles engine the material does not exist. The solution appears to be that I must create the material a second time in the Shading workspace.

Question: how can I rework my code (below) so that the material gets added in the Shading workspace as well?

def add_plane_material(MaterialsIndex, MaterialName, R, G, B):
    bpy.ops.material.new()
    bpy.data.materials[MaterialsIndex].name=MaterialName
    bpy.data.materials[MaterialName].diffuse_color=(R,G,B,1)
    bpy.context.object.data.materials.append(bpy.data.materials[MaterialName])

```
$\endgroup$
3
  • 1
    $\begingroup$ Eevee and Cycles both offer a wide variety of materials. Do you want a diffuse material (this is probably the closest to the basic material used by the workspace engine)? $\endgroup$
    – Robert Gützkow
    Jul 23 '19 at 20:32
  • $\begingroup$ As a noob, the finer points of "diffuse material" versus other materials is kind of lost on me. But the above code thus far gives me a material I want and thus I am hoping to replicate it as closely as possible with the Eevee and Cycles engines. $\endgroup$
    – vndep
    Jul 23 '19 at 20:35
  • 1
    $\begingroup$ I hope my answer comes close to what you had in mind. $\endgroup$
    – Robert Gützkow
    Jul 23 '19 at 21:23
1
$\begingroup$

The following script allows you to create a material with the colors you'd like and assign it to a specific object. The material is only created once, if another material with the same name already exists that one is used. If it finds the expected shader node it sets the desired color. The first argument is the object you want the material assigned to, which can be retrieved e.g. through bpy.data.objects['NameOfYourObjectHere'].

def add_material(obj, material_name, r, g, b):
    material = bpy.data.materials.get(material_name)

    if material is None:
        material = bpy.data.materials.new(material_name)

    material.use_nodes = True
    principled_bsdf = material.node_tree.nodes.get('Principled BSDF')

    if principled_bsdf is not None:
        principled_bsdf.inputs[0].default_value = (r, g, b, 1)  

    obj.active_material = material
$\endgroup$
1
  • $\begingroup$ Thanks - that works well; now the material shows up in the shading workspace as well as in layout. $\endgroup$
    – vndep
    Jul 23 '19 at 22:10

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.