0
$\begingroup$

I have a material setup like this:

enter image description here

I want now to copy this material via python, and change the texture images (so these should be real copies) but the nodegroup should be referenced (so all copied materials should use that one nodegroup instance).

I copied the material like this:

def copyObjectFromSelectedWithTemplateMaterial(newObjectName, newMaterialName, noOfObjects):
    
    orig = bpy.context.selected_objects[0]
    copy = copyActiveObject()
    copy.name = newObjectName
    copy.location.y = orig.location.y + 2 * noOfObjects
    
    mat = bpy.data.materials["TemplateMaterial"]
    
    # problem: node group is not linked to original...
    copy.active_material = mat.copy()
    copy.active_material.name = newMaterialName
    
    bpy.context.collection.objects.link(copy)
    
    return copy

def copyActiveObject(): # real copy, not linked copy

    orig = bpy.context.selected_objects[0]
    return bpy.data.objects.new("my new object", orig.data.copy())

Unfortunately i don't know how to make the nodegroup just a reference...so just the opposite of clicking the button "make single user". Hope it is understandable.

$\endgroup$

1 Answer 1

2
$\begingroup$

You can't make the node group, as shown, "just a reference".

You can reuse the entire material. That will be reference counted, but if you change the material, every user sees the change. That's when "make single user" comes into play. That function copies the original thing and gives it a new name of the form oldname.xxx where xxx is a 3 digit number with leading 0s.

The closest you can come is to make a node group from the nodes. In python you do this with bpy.ops.node.group_make() This creates a new node from the selected nodes that can be used by multiple users. But again, if you change the nodes inside the group, every user of the group will see the change; and you need "make single user" on an instance to be able to make a copy that stands alone.

This example is taken from "Create a node group from an existing tree" on devtalk:

active_area = context.area
active_area_type = active_area.type
active_area.type = "NODE_EDITOR"
active_area.ui_type = "ShaderNodeTree"
context.space_data.node_tree = your_tree_name
bpy.ops.node.group_make()
active_area.type = active_area_type
$\endgroup$

You must log in to answer this question.

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