1
$\begingroup$

I have a mesh object, and I want to fiddle with its material properties in Cycles through a script. I have tried this:

I created an object:

g_d = bpy.data.meshes.new(name="GroundM")
g_o = bpy.data.objects.new(name="GroundO", object_data = g_d)
scene.objects.link(g_o)
g_o.location = (0,0,0)
g_o.select = True
scene.objects.active = g_o

Next I define the material to be made, and what to do with its nodes

def create_cycles_material(name):

    mat = bpy.data.materials.new(name)
    mat.use_nodes = True
    nodes = mat.node_tree.nodes

    node = nodes['Diffuse BSDF']
    node.location = 600, 120
    pass   # Some more node-engineering here

Next, I define a function that should link a material to a mesh object:

def setMaterial(ob, mat):
    me = ob.data
    me.materials.append(mat)

Finally I make the material and assign it to the mesh object g_o:

ColoredGround = create_cycles_material('GroundCol')
setMaterial(g_o, ColoredGround)

The object appears as it should be, and the material with all its specified nodes is created somehow, but I still have to go to the object afterwards and manually add a material and then select the material that I scripted, to assign it to my mesh. I did look into this answer applying to Blender Internal render as well but I still can´t figure out why my script does not work.

$\endgroup$
  • 1
    $\begingroup$ Does your "passless" create_cycles_material(...) return the material created? ortherwise it will just set it to None which will appear as an empty slot. $\endgroup$ – batFINGER Oct 4 '17 at 16:32
1
$\begingroup$

As batFINGER mentioned, you just forgot the return statement. I tried out your code (and had to modify it a bit, because I got the error that 'scene' was not defined) and it worked fine when I added return mat to the function create_cycles_material.

Here's the ready to use code:

import bpy

def main():
    g_d = bpy.data.meshes.new(name="GroundM")
    g_o = bpy.data.objects.new(name="GroundO", object_data = g_d)
    scene = bpy.data.scenes[0]
    scene.objects.link(g_o)
    g_o.location = (0,0,0)
    g_o.select = True
    scene.objects.active = g_o

    ColoredGround = create_cycles_material('GroundCol')
    setMaterial(g_o, ColoredGround)

def create_cycles_material(name):

    mat = bpy.data.materials.new(name)
    mat.use_nodes = True
    nodes = mat.node_tree.nodes

    node = nodes['Diffuse BSDF']
    node.location = 600, 120
    #pass   # Some more node-engineering here
    return mat

def setMaterial(ob, mat):
    me = ob.data
    me.materials.append(mat)

if __name__ == '__main__':
    main()
$\endgroup$

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.