1
$\begingroup$

I would like to rewrite the following script so that I can set the color of the material using a hex value; currently it works with RGB.

A search of the literature provides no suggestions as to how to proceed.

Any advice would be much appreciated!

def add_material(obj, material_name, r, g, b):
    material = bpy.data.materials.get(material_name)
    if material is None:
        material = bpy.data.materials.new(material_name)
    material.use_nodes = True
    principled_bsdf = material.node_tree.nodes['Principled BSDF']
    if principled_bsdf is not None:
        principled_bsdf.inputs[0].default_value = (r, g, b, 1)  
    obj.active_material = material
$\endgroup$
3
$\begingroup$

You can convert a hex value to rgb like below, using shift and bitwise and operator, then divide it by 255 to get a value between 0 and 1.

import bpy

def hex_to_rgb( hex_value ):
    b = (hex_value & 0xFF) / 255.0
    g = ((hex_value >> 8) & 0xFF) / 255.0
    r = ((hex_value >> 16) & 0xFF) / 255.0
    return r, g, b

def add_material(obj, material_name, h):
    material = bpy.data.materials.get(material_name)
    if material is None:
        material = bpy.data.materials.new(material_name)
    material.use_nodes = True
    principled_bsdf = material.node_tree.nodes['Principled BSDF']
    if principled_bsdf is not None:
        principled_bsdf.inputs[0].default_value = (*hex_to_rgb(h), 1)  
    obj.active_material = material

h = 0xE7E7FF

obj = bpy.context.object

add_material( obj, "test", h )

Note: you won't obtain the same value in the UI as the hex value is shown gamma corrected.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.