1
$\begingroup$

So im having an issue where I want to change one value in a node for all different materials of the selected objects, so i wrote this code:

æenter image description here

but it just doesnt work, please can some help me understand whats going on?

$\endgroup$

1 Answer 1

2
$\begingroup$

You're trying to iterate the wrong way.

Take a look at my code below, I have proposed some variations directly written in the code

import bpy


selected_objects = bpy.context.selected_objects

# Solution A Iterate all object selected:
for o in selected_objects:

    for m in o.data.materials:
        if not m.use_nodes:
            continue

        if m.name != "Your mat name":
            continue

        for n in m.node_tree.nodes:
            if n.name == 'Your Node Name':
                # This:
                n.inputs['your input name'].default_value = 0.25
                # Or this
                n.inputs[0].default_value = 0.25




# Solution B Iterate directly the bpy.data.materials:

for m in bpy.data.materials:
    if not m.use_nodes:
        continue
    if mat.name != "Your mat name": # only if you know your mat name
        continue
    
    node_tree = m.node_tree
    nodes = node_tree.nodes

    # This 
    for n in m.node_tree.nodes:
        if n.name == 'Your Node Name':
            n.inputs['your input name'].default_value = 0.25

    # Or this:
    n = nodes.get("Your Node Name") # This is to be sure the node exists into nodes
    if n:
        n.inputs['your input name'].default_value = 0.25
        # Or 
        n.inputs[0].default_value = 0.25

        # You can also try to get the input by name:
        n_input = n.inputs.get("your input name")
        if n_inputs:
            n_inputs.default_value = 0.25
$\endgroup$
3
  • $\begingroup$ Thanks so much, this helped me! I modified the code a bit for my own personal needs, but its largely the same concept you have written: $\endgroup$ Nov 8, 2023 at 8:48
  • $\begingroup$ import bpy for i in bpy.context.selected_objects: bpy.context.view_layer.objects.active = i for m in bpy.data.materials: if not m.use_nodes: continue node_tree = m.node_tree nodes = node_tree.nodes n = nodes.get("Value") if n: #change m to whatever value you want for the node m=1 n.outputs[0].default_value = m $\endgroup$ Nov 8, 2023 at 8:48
  • 1
    $\begingroup$ Of course, it can be written in many ways, I wanted to put in a few variations, just to give some more ideas. The important thing was to understand how to iterate on your Objects/Materials/Nodes. Use cases may vary from situation to situation. $\endgroup$
    – Noob Cat
    Nov 8, 2023 at 17:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .