Update blender material after modifying nodes

I wrote a small script that adds a Material and Output node to a materials Node tree (for blender internal, that is). It also selects a material in the Material node. However, this is only updated in the material panel after I switch to the compositor and select the material.

How do I trigger this update directly from code?

What i’ve tried:

  1. mat.update_tag()
  2. mat.node_tree.update_tag()
  3. bpy.context.scene.update()
  4. mat.use_nodes = False
    mat.use_nodes = True
  5. node.socket_value_update(bpy.context)

To reproduce the situation:

  1. create an object and a material
  2. switch to Scripting view and run this script:

import bpy

'''
Adds material nodes to all blender materials, so that the "use nodes" flag does not need
to be toggled in all the files
'''

for mat in bpy.data.materials:
    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    existing_node_types = dict((x.bl_idname, x) for x in nodes)
    if 'ShaderNodeMaterial' in existing_node_types:
        material_node = existing_node_types['ShaderNodeMaterial']
    else:
        material_node = nodes.new(type='ShaderNodeMaterial')
        material_node.material = mat
    if 'ShaderNodeOutput' in existing_node_types:
        output_node = existing_node_types['ShaderNodeOutput']
    else:
        output_node = nodes.new(type='ShaderNodeOutput')
    
    mat.node_tree.links.new(material_node.outputs['Color'], output_node.inputs['Color'])
    #I've tried several update attempts here, but none worked
    mat.node_tree.update_tag()

  1. in the materials panel of your object, you will see that it is using nodes, but it will say ‘No material node selected’
  2. open the node view to view the materials’ nodes, and suddenly the material will be shown correctly in the materials panel.

If I understand your problem correctly, the problem is caused by the indentation of “material_node.material = mat” this should be executed in both cases. And then you also don’t need mat.node_tree.update_tag()

Thanks for the tip but that’s not the problem. That indentation was intentional (I assumed that when I already have a material node, I don’ t need to tell it where to get the material from)

Here’ s a file to see what I mean
material_node_update.blend (474 KB)

  1. open the file
  2. run the script
  3. look at the material panel
  4. open the compositor in one of the areas
  5. switch the compositor to material, and see the material panel change.

Probably just missing an update event push somewhere.

…I’d say that I’ll look into it but I always say that and never do so you might want to file a bug report.