Define variable names for data set based on layer names

Anyone, especially newbies, asking for help with Photoshop Scripting and Photoshop Automation - as opposed to those contributing to discussion about an aspect of Photoshop Scripting

Moderators: Tom, Kukurykus

jj1979
Posts: 1
Joined: Wed Oct 02, 2024 6:13 am

Define variable names for data set based on layer names

Post by jj1979 »

Instead of going Image -> variable -> define, selecting a layer from the drop down menu, clicking the visibility checkbox and then typing in a name, is there a way (script?) to automate creating visibility variables for every layer in a Photoshop document? Thanks for any help :)

Professional AI Audio Generation within Adobe Premiere Pro - Download Free Plugin here

User avatar
Scriptor
Posts: 29
Joined: Tue Oct 01, 2019 12:07 pm

Re: Define variable names for data set based on layer names

Post by Scriptor »

Is this kind of what you're looking for?

Code: Select all

function hideShowLayersByName(nameString, visibilityFlag) {
    var doc = app.activeDocument; // Get the active document
    var layers = []; // Array to store layers
    
    // Function to recursively add all layers to the array (includes layer sets)
    function getLayers(layerSet) {
        for (var i = 0; i < layerSet.layers.length; i++) {
            var layer = layerSet.layers[i];
            layers.push(layer); // Add each layer to the array
            
            // Check if the layer is a group (LayerSet)
            if (layer.typename === 'LayerSet') {
                getLayers(layer); // Recursively add layers from the group
            }
        }
    }
    
    getLayers(doc); // Start by passing the document

    // Iterate over all layers and show/hide based on the nameString and visibilityFlag
    for (var j = 0; j < layers.length; j++) {
        var layerName = layers[j].name.toLowerCase(); // Get the layer name in lowercase for case-insensitive comparison

        // Check if the layer name contains the specified string
        if (layerName.includes(nameString.toLowerCase())) {
            layers[j].visible = visibilityFlag === 1; // Show if visibilityFlag is 1, hide if it's 0
        }
    }
}

hideShowLayersByName("foo", 0); // This will hide all layers with names containing "foo"
hideShowLayersByName("bar", 1); // This will show all layers with names containing "bar"