# Python 2.8 - how to assign a material in shading versus layout workspace

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])

$$$$

• 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)? Jul 23 '19 at 20:32
• 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. Jul 23 '19 at 20:35
• I hope my answer comes close to what you had in mind. Jul 23 '19 at 21:23

## 1 Answer

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
`
• Thanks - that works well; now the material shows up in the shading workspace as well as in layout. Jul 23 '19 at 22:10