Mass renaming of shaders in the scene

Hi!

I join shaders with .000 extention into one. However, when using Material utilities plugin for that, many objects that were already previously deleted from the scene caused many duplicated shaders being left without original ones. Causing this feature skip them.

If “shader” is missing, remaining “shader.001” and “shader.002” will be skipped by merging feature of Material utilities.

In order to bypass that, I figured I could use a script that would look up duplicated materials, forcibly rename all of them into original name. Probably reshuffling the order, but that doesn’t bother me, as I want to merge them into one shader anyway.

But I’m stuck with the code bit, if anyone could help out!

for o in bpy.context.view_layer.objects:
    for m in o.material_slots:
#           looking up any duplicates
        if "." in m.name:         
#            rename the duplicate found into original name, creating new duplicates in the process, but that's fine
            m.name = "shader"

import bpy

# VARIABLES
REMOVE_INSTANTLY = True
A = []
B = []

# OPERATIONS
for i in bpy.data.materials:
    if i.name[-3:].isdigit():
        A.append(i.name)
    else:
        B.append(i.name)

for a in A:
    for b in B:
        if b in str(a):
            if REMOVE_INSTANTLY == True:
                bpy.data.materials[str(a)].user_remap(bpy.data.materials[str(b)])
                bpy.data.materials.remove(bpy.data.materials[str(a)])
            else:
                bpy.data.materials[str(a)].user_remap(bpy.data.materials[str(b)])

I’ll just throw in a link to the docs for anyone interested, since I don’t often see this method online

https://docs.blender.org/api/current/bpy.types.ID.html#bpy.types.ID.user_remap

user_remap(new_id)

Replace all usage in the .blend file of this ID by new given one

Parameters

new_id (ID, (never None)) – New ID to use

This unfortunately didn’t do anything for me. I use 3.0.2

I’m pretty new to all this, so in this case, I’m not sure how to put this in use.

But thanks anyway for the input, others might find it useful!

Here’s how I figured it out:

I went for Batch rename function under Edit tab

Then made sure it’s set to “Materials”

And Find/Replace tab has checked “Regular expression find”

Then add

.(.*)

image

Which causes every material (either selected or all) to be releaved of any .000, reshuffling all those with the same name, but creating the basic one without .000 numbering

Then when using Material Utility function (L shift + Q, needs to be activated under Addons), all materials in the scene will be linked, as all of them now have their originals!

Set “Auto Rename/Replace” and Hit Ok

image

Done. ALL materials in the scene are linked now.