Notifications
Clear all

[Closed] Delete Empty Layers

I am trying to write a pretty simple script but having some issues and I was hoping someone could point out what’s wrong. All I want to do is iterate through all of the layers and try to delete each one, since you can only delete empty or non-default layers, I figured this was the easiest way to remove empty layers. Here’s the code, it’s erroring and I don’t know why:


   for i=0 to ((layerManager.count)-1) do
   (
   layerobj = LayerManager.getLayer i
   layername = layerobj.name
   layerManager.deleteLayerByName layername
   )
   

EDIT:
Sure enough, two minutes after posting I keep tinkering with it and figure it out, although I don’t quite understand why. What I did was change it so that it iterates through the layers from the highest number to the lowest, and it seems to work now.

for i=((layerManager.count)-1) to 0 by -1 do

If you have any insight as to why it works better that way, It’d be nice to know, thanks!

1 Reply

yes, because when you delete a layer while going through them then your layermanager.count changes to minus 1… So it will error out because it will be initally expecting to loop through the array 5 times, but when you delete something it only wants to go through 4 times so you’ll get an out-of-bounds error. Get it?

var = #(1,2,3,4,5)
var.count

5

deleteItem var 3
var.count

4