This script sorts all layers in a composition by their Z position, moving them into order based on their depth in 3D space. It does the following:
- Collects the Z positions of all layers into an array.
- Sorts the array numerically using a comparison function.
- Reorders the layers in the composition according to the sorted Z positions.
- Handles locked layers by unlocking them temporarily during the sorting process and then re-locks them afterward.
JavaScript
Sort_Layers_by_Z_Positions (0 downloads )
{
var proj = app.project;
var undoStr = "Sort Layers By Z Position";
function compareNums(a, b) {return a - b;}
function sortByZ(comp_layers) {
zz = new Array;
for (o = 1; o <= comp_layers.length; o++) {
zz[zz.length] = comp_layers[o].property("Position").valueAtTime(0, false)[2];
}
zz = zz.sort(compareNums);
allZs = zz.length;
for (n = 0; n < allZs; n++) {
clearOutput();
writeLn("Positions sorted ...");
write("Finding & moving layer " + n + " of " + allZs);
foundOne = false;
itsLocked = false;
thisZ = zz[n];
r = (n + 1);
while (!foundOne) {
if (thisZ == comp_layers[r].property("Position").valueAtTime(0, false)[2]) {
foundOne = true;
if (comp_layers[r].locked) {
itsLocked = true;
comp_layers[r].locked = false;
}
if (n == 0) {
comp_layers[r].moveToBeginning();
} else {
comp_layers[r].moveAfter(comp_layers[n]);
}
if (itsLocked) {comp_layers[n + 1].locked = true;}
} else {
r = (r + 1);
if (r > allZs) {
foundOne = true;
}
}
}
}
clearOutput();
}
if (proj) {
var activeItem = app.project.activeItem;
if (activeItem != null && (activeItem instanceof CompItem)) {
app.beginUndoGroup(undoStr);
var activeCompLayers = activeItem.layers;
sortByZ(activeCompLayers);
app.endUndoGroup();
clearOutput();
write("Sorting Complete.");
} else {
alert("Please select an active comp to use this script");
}
} else {
alert("Please open a project first to use this script.");
}
}