2
$\begingroup$

How do I copy a node from a node_tree.nodes to another ? In document, I see the copy property, but when I call it from interpreter, It causes errors :

>> node = bpy.data.objects[0].data.materials[0].node_tree.nodes['Mix.001']
>>> node
bpy.data...nodes["Mix.001"]

>>> node.copy
Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
AttributeError: 'ShaderNodeMixRGB' object has no attribute 'copy'

>>> node.copy()
Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
AttributeError: 'ShaderNodeMixRGB' object has no attribute 'copy'

>>> node.copy(node)
Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
AttributeError: 'ShaderNodeMixRGB' object has no attribute 'copy'

Document : https://docs.blender.org/api/2.79/bpy.types.Node.html#bpy.types.Node

My blender version is 2.79

$\endgroup$

1 Answer 1

3
$\begingroup$

The copy function really seems to be missing from the Python API. I would suggest to get the bl_idname of the node, create a new instance in the other node tree and then iterate through the default_values of the node's inputs and assign them to the new node.

import bpy


def copy_node(node, target_node_tree):
    # Get the bl_idname to create a new node of the same type
    node_new = target_node_tree.nodes.new(node.bl_idname)

    # Assign the default values from the old node to the new node
    for key, input in enumerate(node.inputs):
        node_new.inputs[key].default_value = input.default_value

    return node_new

For instance, if you would have an active object with two material slots, each with filled with a node based material and you would like to copy the Diffuse BSDF node of the first material into the second one, this could be accomplished by the following code:

if __name__ == "__main__":
    node_tree = bpy.context.object.material_slots[0].material.node_tree
    node_tree_2 = bpy.context.object.material_slots[1].material.node_tree
    node = node_tree.nodes["Diffuse BSDF"]
    copy_node(node, node_tree_2)

This simplified example doesn't check if the materials and nodes actually exist, which should be done in a proper implementation.

$\endgroup$

You must log in to answer this question.

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