1
$\begingroup$

I need to process a bunch of Blend files that contain four objects. For 3 out of the 4 objects (doesn't matter which one is which), I need to duplicate the materials for all material slots and then rename the material to be [obj.name]+[original material name] - [.001 (or .002 or .003)]. How do I do this with python?

$\endgroup$

1 Answer 1

3
$\begingroup$

You aren't very clear in your question, so here's the answer to my understanding of it:

import bpy, re
from bpy import data as D
template = "[{}]+[{}]"
re_pattern = re.compile(r'\.\d{3}$')

mesh_obs = (o for o in D.objects if o.type == 'MESH')
for _, ob in zip(range(3), mesh_obs):
    for slot in ob.material_slots:
        mat = slot.material
        if not mat:
            continue
        new_name = template.format(ob.name, re.sub(re_pattern, '', mat.name))
        mat = mat.copy()
        mat.name = new_name
        slot.material = mat

Some changes to the previous version: Don't use continue and just allow the script to error if there's no material (sometimes getting an error is more useful than silently working incorrectly), don't use regex (for those who aren't fans of it), don't copy the materials on the 4th object, use f-strings rather than a template string:

import bpy, re
from bpy import data as D

mesh_obs = (o for o in D.objects if o.type == 'MESH')
for i, ob in zip(range(4), mesh_obs):
    for slot in ob.material_slots:
        mat = slot.material
        name_parts = ob.name.rsplit(sep='.', maxsplit=1)
        if len(name_parts) == 2 and name_parts[-1].isdigit():
            new_name = f"{name_parts[0]}.{mat.name}"
        else:
            new_name = f"{ob.name}.{mat.name}"
        if i < 3:
            mat = mat.copy()
            slot.material = mat
        mat.name = new_name
$\endgroup$
5
  • 1
    $\begingroup$ "- [.001 (or .002 or .003)]" almost surely means to remove a suffix. $\endgroup$
    – scurest
    May 29, 2022 at 22:15
  • $\begingroup$ Yes, what I meant is to remove the suffix at the end, since all the materials will have unique material names instead. $\endgroup$
    – Hologram
    May 30, 2022 at 7:20
  • $\begingroup$ @Hologram have you tried the code? $\endgroup$ May 30, 2022 at 8:54
  • $\begingroup$ @MarkusvonBroady Yes, I just managed to test it. Thanks for your help, it is very close to what i want. I modified it a little to get the correct names. There's one think it doesn't do correctly, which is to rename the materials for the 4th object. Its materials shouldn't be duplicated, but they should be renamed in the same manner. $\endgroup$
    – Hologram
    May 31, 2022 at 5:29
  • $\begingroup$ I can change the range to be zip(range(4), mesh_obs) and purge orphaned data afterwards. $\endgroup$
    – Hologram
    May 31, 2022 at 5:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .