How to Create a Material Using Python Script

I Just Created a Node Group Using Python Script and I now Just Wan’t to Make a script in which
there should be a Button Which When Clicked Should Create a Material consisting of this Node Group which I Have Already Created. I have already created the layout panel but I don’t Know how to define the operation and call the operation of creation of material
So Please Can Any One Help ??

This operator class adds a material to bpy.data.materials:

class AddMat(bpy.types.Operator):
    """Add a material"""
    bl_idname = "whatever.add_my_material"
    bl_label = "Add My Material"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        
        bpy.data.materials.new("material_name")

        return {'FINISHED'}

Put this in your Panel class to create a button, that calls the operator:

self.layout.operator('whatever.add_my_material')

“whatever” can be what you like. It should be something reasonable. For example “object”, if you are working with objects.

This should answer your other question about operator calls, too.

PS: Don’t forget to register and unregister the classes. :slight_smile:

1 Like