Script: convert layer comps to spritesheet
The goal: Given a file containing multiple layer comps, copy these comps into a new image to make a spritesheet.
The problem: Random errors. The code throws an error on when i run the script through the menu
Error 8800: General Photoshop error occurred. This functionality may not be available in this version of Photoshop.
- The command “Get” is not currently available.
Line: 64
-> sprite.activeHistoryState = sprite.historyStates[curHistory-1];
I have no clue what i am doing wrong, any help appreciated!
My code:
#target photoshop
// Save the current preferences
var startRulerUnits = app.preferences.rulerUnits
var startTypeUnits = app.preferences.typeUnits
var startDisplayDialogs = app.displayDialogs
// Set Adobe Photoshop CS6 to use pixels and display no dialogs
app.preferences.rulerUnits = Units.PIXELS
app.preferences.typeUnits = TypeUnits.PIXELS
app.displayDialogs = DialogModes.NO
var sprite = app.activeDocument
var spritesheet = '';
function main(){
// get the sprite dimensions
var spWidth = sprite.width;
var spHeight = sprite.height;
// get its base history to revert to after merging layers
var curHistory = sprite.historyStates.length
// create the spritesheet file at the right dimensions
spritesheet = app.documents.add(sprite.layerComps.length * sprite.width,sprite.height, 72, "Sprite", NewDocumentMode.RGB, DocumentFill.TRANSPARENT);
// loop through the layercomps in the original sprite file
for( var c = 0; c < sprite.layerComps.length; c++ ){
// set the active document to the sprite
app.activeDocument = sprite
// set the approriate layer comp
sprite.layerComps
.apply(); // attempt to merge the visible elements
try{
sprite.mergeVisibleLayers();
}catch(e){
}
// select the sprite and copy the merged content
sprite.selection.selectAll();
sprite.selection.copy() ;
// work out the correct coords for a selection on the spritesheet
var xPos = spWidth * c;
var selRegion = Array(Array(xPos,0),
Array(xPos + spWidth, 0),
Array(xPos + spWidth, spHeight),
Array(xPos, spHeight),
Array(xPos , 0));
// change the active doc to the spritesheet, add a new layer set and paste the copied data into it
app.activeDocument = spritesheet
var newLayer = spritesheet.layerSets.add();
spritesheet.selection.select(selRegion);
spritesheet.paste() ;
// set the active document back to the sprite and then revert the history to the state when we started
app.activeDocument = sprite;
sprite.activeHistoryState = sprite.historyStates[curHistory-1];
// keep looping if need be
}
}
main();
// Reset the application preferences
app.preferences.rulerUnits = startRulerUnits
app.preferences.typeUnits = startTypeUnits
app.displayDialogs = startDisplayDialogs