0
$\begingroup$

I need help writing a python script for speeding up my workflow, I have this imported object with dozens of broken materials, and I need a way to:

1 - Go through each material nodetree on selected object, delete everything and replace with a random diffuse color, so I can work on it later but have visual reference of parts (like color A its gonna be metal, B wood...);

2 - Join materials with the same name into a single one, keeping the nodetree from the lowest number (like wood, wood.001, wood.002...).

The second one i have found a few similar examples here, the first is what I have no idea how to do.

$\endgroup$
2
  • $\begingroup$ What do you mean with your second point? If an object has multiple materials, then you want the lowest one applied to all faces and the others removed? "Merging materials" is a vague expression. $\endgroup$
    – taiyo
    Sep 9 at 22:43
  • $\begingroup$ Hello and welcome. This is not a regular forum, we are a question and answer site aimed at providing users with assistance along the way, rather than solve the issues for them or present ready made solutions. For commissioning work, job posts or hiring someone, there is a paid work section at Blender Artists Forum. Otherwise rephrase your question so it shows your efforts towards solving the issue, rather than ask for someone to do it for you, so it can be reopened. $\endgroup$ Sep 10 at 0:22

1 Answer 1

2
$\begingroup$

Try this script for your first problem:

import bpy
import random

for obj in bpy.context.selected_objects:
    for material in obj.data.materials:
       
        # remove all existing nodes
        nodes = material.node_tree.nodes
        nodes.clear()
    
        # create the diffuse bsdf node with material output
        diffuse_bsdf_node = nodes.new('ShaderNodeBsdfDiffuse')
        material_output_node = nodes.new('ShaderNodeOutputMaterial')

        # set random color
        diffuse_bsdf_node.inputs['Color'].default_value = (
            random.random(), random.random(), random.random(), 1
        )

        # noodle them together
        material.node_tree.links.new(
            diffuse_bsdf_node.outputs['BSDF'],
            material_output_node.inputs['Surface']
        )
$\endgroup$

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