Dynamic add/delete function?

Find out why the . goes before the /

Moderator: Paul Tuersley

Post Reply
BigMacGyver
Posts: 19
Joined: May 7th, 2013, 6:43 am

Hello guys,

i have tried to solve the following problem myself and most likely i am making matters much more complicated than they actually have to be. Here is what i want to do:

Let's say, i have a variable in my user interface called NumberOfTextLayers that the user can put a number in for. When i click an update button, i want the script to look for the amount of text layers within the selected comp and compare this amount to the value of NumberOfTextLayers. It then needs to either add or delete text layers with the same property as the ones in the comp to match the Number of Layers specified in the variable.

I still have a bit of a problem of understanding the concept of loops. I tried several approaches of looping through arrays to get the indexes for the layers that need to be deleted or added, but its... tricky.

If you know how such a loop would have to be setup or if you have a better idea, please let me know.
beginUndoGroup
Posts: 81
Joined: November 27th, 2012, 6:41 am

A skeleton for your problem. You probably don't need to put "condition" as a parameter (a function on a layer that returns a boolean). I left it open since you dont make it clear what those properties to check are.
Didn't test if it works...

Code: Select all

function f(comp, N, condition) // N: the desired number of text layers
{
    var numLayers = comp.numLayers, numTextLayers = 0, n;
    if (numLayers)
    {
        // loop through the comp layers collection and store some info in case there is something to do.
        var textLayersIndices = [];
        for (var j=1; j<=numLayers; j++)
        {
              if (comp.layer(j) instanceof TextLayer && condition(comp.layer(j))) textLayerIndices[numTextLayers++] = j;
              }
        }

    n = numTextLayers - N;

    if (n === 0) return; // nothing to do

    if (n < 0)
    {
         // -n text layers to add
         n *= -1;
         for (var j=1; j<=n; j++) comp.layers.addText(); // this method actually return a text layer object, so give it a name (var t = comp.layers.addText();) if you need to do things on this new layer before continue
         return;
         }

     else // if (n>0)
     {
          // n text layers to remove (assuming that the layers to remove are the last ones in the comp's layers stack) 
          // delete from highest to lowest index so as to not mess up the indexing
          for (var j=1; j<=n; j++) comp.layer(textLayerIndices[N-j]).remove();
          return;
          }
      }
Post Reply