Skip to content

Instantly share code, notes, and snippets.

@exp111
Created August 24, 2023 09:14
Show Gist options
  • Save exp111/0bc17beb99380152460d8f36ca93ee5b to your computer and use it in GitHub Desktop.
Save exp111/0bc17beb99380152460d8f36ca93ee5b to your computer and use it in GitHub Desktop.
ZenVis attach textures to materials
import bpy
# Get the active object
obj = bpy.context.active_object
# Switch to the Shader Editor workspace
#bpy.context.area.type = 'NODE_EDITOR'
#bpy.context.space_data.tree_type = 'ShaderNodeTree'
# Loop through each material slot
#for i, material_slot in enumerate(obj.material_slots):
for i, material in enumerate(bpy.data.materials):
#material = material_slot.material
if material:
material.use_nodes = True
# Create an Image Texture node
image_texture_node = material.node_tree.nodes.new(type='ShaderNodeTexImage')
# Set the image name based on the material name
#image_name = material.name
#image_path = bpy.path.abspath("//" + image_name + ".png") # Change the extension if necessary
# Load the image
#image = bpy.data.images.load(image_path)
image = bpy.data.images.get(material.name + ".TGA")
image_texture_node.image = image
# Connect the image texture node to the shader
shader_node = material.node_tree.nodes.get('Principled BSDF') # Adjust the shader node name as needed
material.node_tree.links.new(shader_node.inputs['Base Color'], image_texture_node.outputs['Color'])
material.node_tree.links.new(shader_node.inputs['Alpha'], image_texture_node.outputs['Alpha'])
# Arrange nodes for better visibility (optional)
#image_texture_node.location.x = -200
#image_texture_node.location.y = i * -200
# Switch back to the 3D Viewport workspace
#py.context.area.type = 'VIEW_3D'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment