1
$\begingroup$

I have a Python script to append materials from multiple .blend files, I also would like to rename them after append, but bpy.ops.wm.append doesn't have parameter for that and doesn't return appended material. I append multiple materials in loop and they all have same names. Does anyone has any clue how to retrieve name of just appended material in Python?

$\endgroup$
2
  • $\begingroup$ Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. $\endgroup$
    – Community Bot
    Dec 21, 2021 at 14:47
  • $\begingroup$ Does this concept work: append has an autoselect parameter. You could deselect everything, append, and then discover what is selected. It's crude, but there are similar techniques that are needed when using an importer as well. $\endgroup$ Dec 21, 2021 at 16:30

2 Answers 2

3
$\begingroup$

You can append with the Python API without using an op.

import bpy

blendpath = "//path/to/file.blend"
with bpy.data.libraries.load(blendpath, link=False) as (data_src, data_dst):
    data_dst.materials = ["Name of Material To Append"]
mat = data_dst.materials[0]
mat.name = "New Material Name"
$\endgroup$
0
$\begingroup$

To answer your specific question "how to retrieve name of just appended material in Python?":

This is a problem that can come up in various ways when appending or using an importer. The pattern for this is to

  • create a set of all of the things of the type you are going to add
  • add the new things
  • create a set of all of the things of the type you just added

The set difference between those two sets is precisely the list of things you just added.

Here's one way to code this for materials. Your code to append materials would go where the comment is:

import bpy

def create_material_set():
    material_set = set()
    for material in bpy.data.materials:
        material_set.add(material)
    return material_set

before_set = create_material_set()

# Append materials

after_set = create_material_set()

new_materials = after_set - before_set

when that's done, new_materials is a set containing all of the materials that you appended. The last line is how Python computes a set of all the things that are in after_set but are not in `before_set; the set difference.

Sets can be iterated so you can process each new material with a loop like this:

for material in new_materials:
    # Do whatever you want with the material.
$\endgroup$

You must log in to answer this question.

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