Blender Python

From bernie's
Jump to navigation Jump to search

List all the shaders of all the selected objects

Windows, writes to a .txt file. I am using this to plug the values back into AE's cryptomatte material selection tool for ease of use.

import bpy
import os
import tempfile


def export_selected_materials_to_temp():
    selected_objects = bpy.context.selected_objects

    if not selected_objects:
        print("No objects selected.")
        return

    # Collect unique material names in order of appearance
    materials = []
    seen = set()

    for obj in selected_objects:
        for slot in obj.material_slots:
            if slot.material and slot.material.name not in seen:
                seen.add(slot.material.name)
                materials.append(f'"{slot.material.name}"')

    comma_separated = ", ".join(materials)

    # Create a temporary .txt file (delete=False so the external editor can read it)
    with tempfile.NamedTemporaryFile(
        mode="w",
        suffix=".txt",
        prefix="blender_materials_",
        delete=False,
        encoding="utf-8",
    ) as temp_file:
        temp_file.write(comma_separated)
        temp_path = temp_file.name

    print(f"Wrote {len(materials)} materials to: {temp_path}")

    # Open the temporary file with Windows' default .txt handler
    os.startfile(temp_path)


if __name__ == "__main__":
    export_selected_materials_to_temp()