Script iterating through layers stops halfway


Question

I'm trying to iterate through every layer in a document and for some reason my script only goes through the first half (13 out of 25) and then at 14 it says that the element doesn't exist. Could you guys help me figure out why? Below is the code snippet which goes through each layer

function processLayers(extension)
{
    var doc = app.activeDocument;
    //go through each layer and create a folder
    alert('length is ' + doc.artLayers.length);
    var length = doc.artLayers.length;
    for (var layer = 0; layer < length; layer++)
    {
        var folderName = generateFolderName(doc.artLayers[layer].name, extension);
        //create folder in photoshop with folderName
        var folder = doc.layerSets.add();
        folder.name = folderName;
        doc.artLayers[layer].move(folder, ElementPlacement.INSIDE);     
    }
}
1
1
8/13/2013 9:33:00 PM

Since I don't have a working copy of your script this is a little difficult for me, but I wrote a script before and here's a function that goes throw and hides all layers:

function hideLayers(ref) {
    var len = ref.layers.length;
    for (var i = 0; i < len; i++) {
        var layer = ref.layers[i];
        if (layer.typename == 'LayerSet') hideLayers(layer);
        else layer.visible = false;
    }
}

You'll notice that it simple grabs the length of the layers object, and then iterates over each layer. In that regard out scripts are nearly identical. If a layer group is encountered (as check by the if statement) then it does a recursive call to hide all nested layers. (Also my ref parameter is activeDocument).

What I would suggest, for debugging purposes, is see if you can run my function without any errors. If so, then you know the issue isn't with iterating over all the layers, but rather with the logic you are trying to execute on each layer, and then make sure that whatever logic you're trying to use is valid on that type of layer (raster, text, shape, etc.)

Another technique would be to fill your loop with helpful alerts (or better yet just logs or breakpoints), and check the value of the variables as they are coming through.

3
8/14/2013 4:31:00 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow


Website under construction!!!
^