Make Materials Single-User via code?

Hi All,

I have a material that I want to use as a base source for a bunch of objects. So I want to clone the material then make it unique. In the GUI interface I would just click the little button next to the material to make a single-user copy. But how do you do that in code? I notice that button has no API tool tip.

Consider this.


import bpy

ob_cube = bpy.data.objects["Cube"]
mat_cube = ob_cube.material_slots[0].material

# Try to make a new copy of the material before I assign it to the mesh.
mat_sphere = mat_cube
mat_sphere.name = "mat_Sphere"

ob_sphere = bpy.data.objects["Sphere"]
ob_sphere.data.materials.append(mat_sphere)

# At this point the materials are still linked.

If I change the color of the material for my sphere, the cube color will change as well, because they are linked.

I think you should use


new_material = bpy.data.materials['Material'].copy()
# then you will have to do the same with every single texture of the material.

I’d go for


mat_sphere = mat_cube.copy()

since that seems to be what make single user does.

Thank you both, I’ll give that a try.

Was noticing this post. Quite old but I thought I’d paste something others who stumble across this can directly cut and paste into the code editor and get results:

This will give all selected objects their own individual material from the shared material.


sel = bpy.context.selected_objects
for ob in sel:
    mat = ob.active_material
    if mat:
         ob.active_material = mat.copy()

This will give all selected objects entirely unique materials, textures and images so each object’s material may be truly edited without affecting another’s.


import bpy

sel = bpy.context.selected_objects
for ob in sel:
    mat = ob.active_material
    if mat:
        ob.active_material = mat.copy()
        
        for ts in mat.texture_slots:
            try:
                ts.texture = ts.texture.copy()
                
                if ts.texture.image:
                    ts.texture.image = ts.texture.image.copy() 
            except:
                pass

2 Likes

Thank you for this!! Much simpler than I thought!!