2
$\begingroup$

I'm writing a script that creates a few bpy.data.textures objects, adds textures to them then adds a few custom properties. These textures will then be applied to the materials in the scene but before export, I need to get those properties again.

I found a code that gets all texture nodes from scene objects but I don't understand how to get the data object from the 'TEX_IMAGE' node.

import bpy

textures = []
for ob in bpy.data.objects:
    if ob.type == "MESH":
        for mat_slot in ob.material_slots:
            if mat_slot.material:
                if mat_slot.material.node_tree:
                    textures.extend([x for x in mat_slot.material.node_tree.nodes if x.type=='TEX_IMAGE'])
                    
print(textures)
```
$\endgroup$
1
  • $\begingroup$ I came up with a rather cumbersome solution, first, create a set with all bpy.data.textures , then create a loop where image_texture_node.image compared with data_texture.image $\endgroup$ Commented Feb 12, 2022 at 2:44

1 Answer 1

3
$\begingroup$

I came up with a code similar to this that at least works

import bpy

def get_textures_from_the_material(blender_material):
    textures = []
    if blender_material:
        if blender_material.node_tree:
            for tn in blender_material.node_tree.nodes:
                if tn.type == 'TEX_IMAGE':
                    textures.append(tn)
    return textures


texture_data = [td for td in bpy.data.textures]
textures = set() 
meshes = {ob.data for ob in bpy.data.objects if ob.type == 'MESH'}
for ob in meshes:
    obt = get_textures_from_the_material(ob.materials[0])
    for tn in obt:
        for td in texture_data:
            if tn.image == td.image:
                textures.add((td))
$\endgroup$
1
  • $\begingroup$ I think this is the preferred way to do it. You could shave off a few lines in the algorithm but all in all this looks to me like the most straightforward way to achieve your goal. $\endgroup$
    – Gorgious
    Commented Feb 13, 2022 at 17:54

You must log in to answer this question.

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