1
$\begingroup$

Basically I'm trying to get every material in every object inside a collection, then randomise its colors. Except, I get the AttributeError which goes "Writing ID classes in this context is not allowed" It returned "Shader Nodetree, NodeTree datablock, error setting NodeSocketColor.default_value" this

I have no Python knowledge and less about Blender stuff, so here

import bpy
import random

for collection in bpy.data.collections:
    if collection.name  == "spect":
        for object in collection.all_objects:
            for material in object.data.materials:
                print("v")
                r = random.randint(0, 255)
                g = random.randint(0, 255)
                b = random.randint(0, 255)
                a = 1
                nodes = material.node_tree.nodes
                bsdf = nodes.get("Principled BSDF")
                bsdf.inputs[0].default_value = (r, g, b, a)

This is probably pretty stupid to ask, but, lol.

$\endgroup$
2
  • 1
    $\begingroup$ Hello & welcome to blender.stackexchange.com. No question that is formulated in an understandable way is stupid! I'm sure there are some Python professionals here who will be happy to help you. $\endgroup$
    – quellenform
    Commented Nov 25, 2022 at 20:55
  • 1
    $\begingroup$ @quellenform: well...i cannot subscribe your comment...but this question is totally satisfying and can be answered ;) $\endgroup$
    – Chris
    Commented Nov 26, 2022 at 8:33

1 Answer 1

1
$\begingroup$

try this:

import bpy
import random

for collection in bpy.data.collections:
    if collection.name  == "spect":
        for object in collection.all_objects:
            if object.type == "MESH":
                for material in object.data.materials:
                    print("v")
                    r = random.uniform(0,1)
                    g = random.uniform(0, 1)
                    b = random.uniform(0, 1)
                    a = 1
                    nodes = material.node_tree.nodes
                    bsdf = nodes.get("Principled BSDF")
                    bsdf.inputs[0].default_value = (r, g, b, a)

Note: colors in Blender are defined from 0 to 1. Not 0 to 255.

You looped over "all objects" which also can have objects like empties (which don't have materials), so i added an if here for the type "mesh".

Be aware that this code prerequisites that the object has a material and the material has the node with the name "Principled BSDF". So make sure that this is the case. (or insert another if - and if it isn't there maybe do "continue" and print an error like " for object (name) material-node not found" or whatever.

$\endgroup$

You must log in to answer this question.

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