Applescript - how to select layer by name?

Talk about Pixelmator Pro, share tips & tricks, tutorials, and other resources.
User avatar

2021-10-31 05:19:08

I'm having a hard time figuring out how to select a layer by name. I have the following structure
- bases
-- base_1
-- base_2
-- base_3
- flowers
-- flower_1
-- flower_2
-- flower_3
Doing the following gives the an error:
tell application "Pixelmator Pro"
	set exportLocation to choose folder with prompt "Please choose where you'd like to export the images:"
	set totalImages to 8
	set counter to 0
	
	tell the front document
		
		repeat totalImages times
			set visible of every layer to false
			
			set counter to counter + 1
			
			set visible of (select (layer whose name is equal to "base_" & (random number from 1 to 3))) to true
                        set visible of (select (layer whose name is equal to "flower_" & (random number from 1 to 3))) to true
                        export for web to ((exportLocation as text) & "flower_" & counter & ".png") as PNG
		end repeat
	end tell
end tell
I get the following error: "error "Can’t get layer whose name = \"base_1\"." number -1728"
User avatar

2021-11-02 10:18:23

Hey there! The trouble you're having is due to the fact that AppleScript checks the top-level list of layers, which is, I think, standard for any nested structure like this. And that goes for both AppleScript and (I'd hazard a guess) most programming, too. A layer list is basically an array and nested layers are sub-arrays inside those arrays. These structures can be potentially very very deep, so checks like this aren't recursive by default. That's not to say that this is difficult to program or implement – it's not – it's just that standard commands are designed to work on top-level structures.

In your case, it would be enough to change the set visible bit to this:
set randomBaseLayer to layer named ("base_" & (random number from 1 to 3)) in group layer named "bases"
set randomFlowerLayer to layer named ("flower_" & (random number from 1 to 3)) in group layer named "flowers"
set visible of randomBaseLayer to true
set visible of randomFlowerLayer to true
I've also refactored the code a little to make everything slightly more readable. Hope that helps!