# Blender 2.8 (python) - How to set material color using hex value instead of RGB

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

• Sep 18 '19 at 16:08

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

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