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$
2
$\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.

| improve this answer | |
$\endgroup$
  • $\begingroup$ Hi Lemon I hope you will excuse me for this disappointment, but this Hex value does not coincide with the Hex value returned by the node color input, in fact if we check the Hex result of this conversion is F4F4FF while your input is E7E7FF $\endgroup$ – Noob Cat Nov 23 '19 at 2:24
  • $\begingroup$ @Pastrokkio, yes as said in the note at the end of the answer the value is gamma corrected in the node field. $\endgroup$ – lemon Nov 24 '19 at 7:29
  • $\begingroup$ Hi , I would like to point out that I received the correct answer to this link, so it can be useful for the comunity blender.stackexchange.com/questions/158896/… $\endgroup$ – Noob Cat Nov 24 '19 at 18:05

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.