2
$\begingroup$

I want to rename my Material slots for a series of objects. In another question, someone suggested that I use this code:

gen = (s for s in ["_Spring", "_Summer", "_Winter", "_Autumn"])
 
bpy.data.objects[0].name = bpy.data.objects[0].name + ".000"
 
for oj in bpy.data.objects:
    s = next(gen)
    name = oj.name[: -4]
    oj.name = f"{name}{s}"
    oj.data.name = oj.name
    oj.material_slots[0].material.name = f"{name}_leaf{s}"
    oj.material_slots[1].material.name = f"{name}_trunk{s}"

Some objects that I need to process have a third slot called "Leaf_2". How could I add a check which, if the slot exists renames the slot similar to how slot 0 and 1 are renamed? And if it there is no such slot, don't modify nor create one. How could that be achieved?

$\endgroup$
1
  • 1
    $\begingroup$ I've modified your question to use StackExchange formatting for the script. If you start with a line consisting of three back-tick characters and end with another one, everything in between is treated as source code. $\endgroup$ Apr 22, 2022 at 22:01

1 Answer 1

2
$\begingroup$

There is a Python idiom for this:

if thing:
    do something

That means 'if this thing has a value other than None then do something'.

Applying this to material slots in your code you would get

if oj.material_slots[2].material:
  oj.material_slots[2].material.name = f"{name}_leaf_2{s}'

By the way, as an aside, "Code is read far more often than it is written." That being true, please use longer variable names for readability. Also, if you are going to use short names, be aware that Blender Python has some ad-hoc conventions, such as using obj as the abbreviation for an object.

$\endgroup$
1
  • $\begingroup$ Ah yes, thanks a lot! That's something I will definitely keep in mind, the cleaner the code the easier it is to manage. $\endgroup$
    – Hologram
    Apr 23, 2022 at 7:22

You must log in to answer this question.

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