Skip to main content
Known Participant
October 5, 2019
Answered

Conditional script for number of layers

  • October 5, 2019
  • 2 replies
  • 1911 views

Hello, 

first of all I know nothing about scripting so if my question is some kind of nonsense, sorry fot that.

I would like to create an action in Ps during which I need to insert a conditional that says "If the document has 3 or more layers, launch XX action." Is it possible to make it done? Default Ps conditionals dont seem to offer that. I was wondering if there is maybe some script for this?

 

Thanks

This topic has been closed for replies.
Correct answer Tom Winkelmann

You can test this script (before you have to change name of action and action set in the script)...

#target photoshop

var s = countLayers(app.activeDocument);

if (s.layers.all >= 3){
    app.doAction('name of action', 'name of action set') // change name of action and action set
    } 
else {
    alert("Less than 3 layers found.")
    }  

function countLayers(item,stats){
  var i;
  if (!stats) stats={layers:{on:0,off:0,all:0},groups:{on:0,off:0,all:0}};
  stats.layers.all += (i=item.layers.length);
  while (i--) stats.layers[item.layers[i].visible ? "on" : "off"]++;
  stats.groups.all += (i=item.layerSets.length);
  while (i--){
    stats.groups[item.layerSets[i].visible ? "on" : "off"]++;
    countLayers(item.layerSets[i],stats);
  }
  return stats;
}

 

2 replies

Stephen Marsh
Community Expert
Community Expert
October 5, 2019

What type of layers?

 

#target photoshop
var doc = app.activeDocument;
var layerCount = doc.layers.length
if (layerCount >= 3) {
    alert('Greater than or equal to 3 layers');
    } 
else {
    alert('Less than 3 layers')
    }  
ParanoicAuthor
Known Participant
October 6, 2019

Everything works okay, but what if I want exact number of layers (not 3 or more, just 3). I thought that deleting ">" and keeping "=" will solve the problem, but apparently not.

 

Edit: okay "==" will do 

ParanoicAuthor
Known Participant
October 6, 2019
Edit: okay "==" will do 🙂
Tom Winkelmann
Tom WinkelmannCorrect answer
Inspiring
October 5, 2019

You can test this script (before you have to change name of action and action set in the script)...

#target photoshop

var s = countLayers(app.activeDocument);

if (s.layers.all >= 3){
    app.doAction('name of action', 'name of action set') // change name of action and action set
    } 
else {
    alert("Less than 3 layers found.")
    }  

function countLayers(item,stats){
  var i;
  if (!stats) stats={layers:{on:0,off:0,all:0},groups:{on:0,off:0,all:0}};
  stats.layers.all += (i=item.layers.length);
  while (i--) stats.layers[item.layers[i].visible ? "on" : "off"]++;
  stats.groups.all += (i=item.layerSets.length);
  while (i--){
    stats.groups[item.layerSets[i].visible ? "on" : "off"]++;
    countLayers(item.layerSets[i],stats);
  }
  return stats;
}

 

ParanoicAuthor
Known Participant
October 5, 2019
Absolutely brilliant, thank you very much.