[Script] MAT-Switch

Hy!
This is a simple material color switcher script.
If a material exist: choose a material id and change color over color picker or color wheel
Works with Blender Render and Cycles as well.


import bpy
from bpy.props import *


class VIEW3D_TP_SetColors(bpy.types.Operator):
    """switch material color by choosen material id"""  
    bl_idname = "tp_mat.set_colors"
    bl_label = "Set Color"
    bl_options = {'REGISTER', 'UNDO'} 

    @classmethod
    def poll(self, context):
        if context.object and context.object.type == 'MESH':
            return len(context.object.data.materials)

    new_swatch = FloatVectorProperty(name = "Color", default=[0.0,1.0,1.0], min = 0, max = 1,  subtype='COLOR')
    index_count = bpy.props.IntProperty(name="MAT-ID",  description="set material index", min=0, max=100, default=0) 
 
    # DRAW REDO LAST PROPS [F6] # 
    def draw(self, context):
        layout = self.layout
        col = layout.column(align = True)
   
        box = col.box().column(1) 
        
        row = box.row(1)
        row.prop(self, "index_count")  
        row.prop(self, "new_swatch", text="")     
       
        box.separator() 

    def execute(self, context):
        # material check with mat-id and color picker type
        #if len(context.object.material_slots) > 0:
            ob = bpy.context.object
            try:
               mat = ob.data.materials[self.index_count]
            except IndexError:
                print(self)
                self.report({'INFO'}, "No further Material!")  
                pass
            else:        
                if bpy.context.scene.render.engine == 'BLENDER_RENDER':                   
                    words = self.my_swatch
                    color = (float(words[0]), float(words[1]), float(words[2]))            
                    mat.diffuse_color = color

                else:
                    node=mat.node_tree.nodes['Diffuse BSDF']         
                    words = self.my_swatch
                    RGB = (float(words[0]), float(words[1]), float(words[2]),1) 
                    node.inputs['Color'].default_value = RGB
        #else:
            #pass
               
        return{'FINISHED'}   


# REGISTRY #
def register():    
    bpy.utils.register_module(__name__)

def unregister():
    bpy.utils.unregister_module(__name__)

if __name__ == "__main__":
    register()
        

Easy to add this to the end of an mesh creation script that different materials applies…

1 Like

Very good mkbreuer , i will analyse it but that’s sound good!
I am working on a color patern harmonie pie!
Best week-end, my Friend!
Spirou4D