0

Not sure if I'm doing this right. I'm trying to locate a layer. I can normally do that by group name & layer name. However that does present problems if there are duplicate names. So instead I'll try and find their unique layer ID.

I think this is correct:

var srcDoc = app.activeDocument;
var numOfLayers = srcDoc.layers.length;

// main loop
for (var i = numOfLayers -1; i >= 0  ; i--)
{
   var ref = new ActionReference();
   ref.putIndex( charIDToTypeID( "Lyr " ), i);
   var layerDesc = executeActionGet(ref);
   var layerID = layerDesc.getInteger(stringIDToTypeID('layerID'));
   var currentLayer = srcDoc.layers[i].name;
   alert(layerID + " " + currentLayer);
}

... Only I expected the ID to be a larger random string, not a int. Firstly, have I got this right? And secondly is there a way to get the layer ID from the activeLayer?

Ghoul Fool
  • 6,249
  • 10
  • 67
  • 125

1 Answers1

1

IDs are interegers in PS and they are unique for a document only: they always start at 1 and then new layers and layer operations change ID counter by +1 so it's normal to have IDs in hundreds after a while.

To get an id of the active layer, change the reference to target:

var ref = new ActionReference();
ref.putEnumerated(charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt')); // reference is active layer
var layerDesc = executeActionGet(ref);
var layerID = layerDesc.getInteger(stringIDToTypeID('layerID'));
alert(layerID);

P.S. this will work only with one active layer. For multiple layers you'll have you use a function I posted here: Get selected layers

P.P.S. note that your original code won't work with groups: indices of DOM and indices of AM aren't the same. You need to traverse layers in AM list to get proper indices.

Ghoul Fool
  • 6,249
  • 10
  • 67
  • 125
Sergey Kritskiy
  • 2,199
  • 2
  • 15
  • 20
  • I'm aware of having to do a recursive loop for groups, but I wanted to keep it simple :) – Ghoul Fool Sep 08 '20 at 13:00
  • Wll, even recursive loop won't give you correct indices: groups take 2 indices in AM (start and end). Just embrace AM, come to the dark side :D – Sergey Kritskiy Sep 08 '20 at 13:03
  • Sorry for late feedback, I got distracted... I think things may have changed now as I get the error `cITD is not a function` However, you can use `layerID = app.activeDocument.activeLayer.id;` – Ghoul Fool Dec 03 '21 at 11:14
  • 1
    @GhoulFool ah sorry, `cTID()` is a `charIDToTypeID()` — a common-ish abbreviations. I think layer ID as a prop of an ArtLayer was added quite recently — at least it wasn't a thing several versions ago – Sergey Kritskiy Dec 03 '21 at 17:05
  • app.activeDocument.activeLayer.id was added around 2018, I'd not seen it before. – Ghoul Fool Dec 03 '21 at 19:33