Python - Create single-user copy of all materials on object

Hi, I have several hundred materials on one object (for a specific game engine, don’t ask lol)
I need to make all of the materials a single-user copy, and then rename each one
I am trying to use the following python code, but just…nothing happens
What have I missed?

selected = bpy.context.selected_objects
for obj in selected:
   materials = obj.data.materials
   for mat in materials:
      mat = mat.copy()
import bpy
selected = bpy.context.selected_objects
for obj in selected:
   materials = obj.data.materials
   mat_dict = {mat.name: i for i, mat in enumerate(materials)}
   for mat in materials:
       obj.data.materials[mat_dict[mat.name]] = mat.copy()
       obj.select_set(False)
       obj.select_set(True)

Welcome to BA :slight_smile: This code works, I tweaked it for you :slight_smile: You have to assign the new material to the slot, and toggle the selection for the Material slots to update

1 Like

Thank you so much! This seems to work exactly as I needed :slight_smile:
This is my first attempt at automating anything in blender, so I’m unfamiliar with the syntax, although I have decent basic python knowledge

How would I set the name of the material in a slot? I need to rename each material during the loop to a custom string (I know how to get the custom string etc, I’m just unsure of the exact syntax for renaming a material in a slot)

You can do that with a one-liner added to my previous code:

...
for mat in materials:
       ...
       obj.data.materials[mat_dict[mat.name]].name = "custom_name"

Note that this will, by itself, cause problems, since it will assign the same name to all material slots. You could instead use something like

obj.data.materials[<SLOT_NUMBER>].name = "custom_name"

outside of the for loop. You could also just add a number to the end of the custom name, in the for loop:

index += 1
materials[mat_dict[mat.name]].name = "".join(["custom_name", str(index)])

The important thing is that material.name attribute, how you assign to it is up to you.

Blender Python isn’t too bad, it has some idiosyncracies but it’s too not hard to pick up :slight_smile: Luckily you’ve got a great community of people ready to help, feel free to post any questions here :smiley: