Create and assign materials to selected objects

HI guys

Task: create and assign materials for selected objects where material name = object name.
I.e. we select 3 objects, “box”, “cool_box”, “awesome_model” and after script object “box” will have material named “box”, “awesome_model” will have material named “awesome_model” and so on.

Maybe some one have an examples? Im not familiar with python at all.
Currently i realize how to rename already created and assigned material to object name, but still dont get how to create and assign material automatically on for loop.

i would suggest look into easybpy. It’s really easy and can get job done for you if you are not in to scripting. https://youtu.be/ybnapDe4-Ts
but here’s the code.
Select some objects and run script.
Edit: Here there is no check if object is mesh/curve or not. So if you select camera/lights which can not have material it’ll throw error.

import bpy

selected_objs = bpy.context.selected_objects

for obj in selected_objs:
    #get name of object
    name = obj.name
    
    # check if object has material same as object name
    # if there is then continue to next object
    if name in obj.data.materials:
        continue
    
    #create new material with name of object
    new_mat = bpy.data.materials.new(name)
    
    #add new material to object
    obj.data.materials.append(new_mat)
    #added material will be last in material slots
    #so make last slot active
    obj.active_material_index = len(obj.data.materials) - 1 


1 Like

Thank you Pavan, works as it should. And thanks for link you youtube channel :slight_smile: