Creative Communities of the World Forums

The peer to peer support community for media production professionals.

Activity Forums Adobe After Effects Expressions For loop to count layers not behaving as it should

  • For loop to count layers not behaving as it should

    Posted by Doc Byrne on March 19, 2024 at 11:03 am

    Hi folks,

    I’m working on a project and I need to count the number of layers with a specific name and display it as a number on screen. I’ve been using a for loop but unfortunately, I can’t quite get it right and I have the feeling I’m missing a condition in the code but I can’t figure out what it is.

    When I apply the following code to a text layer, it displays the correct number when I add or delete a layer called Depth provided it happens below the text layer. But if I add or delete layers above the text layer, the number increases or decreases the number, regardless of what the layer is called.

    I know it’s probably something obvious but I’m stumped. Can anyone help please?

    var result = 0;

    for (var i = 1; i <= thisComp.numLayers; i++) {

    var compLayer = thisComp.layer(i);

    var layerName = compLayer.name;

    if (layerName == "Depth") {

    result+=i;

    break;

    }

    }

    result;

    Brie Clayton replied 3 weeks, 1 day ago 3 Members · 3 Replies
  • 3 Replies
  • Julian Chojnacki

    March 19, 2024 at 1:27 pm

    Hi! You’re almost there, but instead of adding the layer index i to result, you should add 1 each time you find a layer named “Depth”. Also, remove the break statement to ensure the loop continues to check all layers even if your condition is met.

  • Doc Byrne

    March 20, 2024 at 1:17 pm

    That’s brilliant! Thanks a million for this, Julian. Can’t believe I got an i and a 1 confused 🤦‍♂️

    It’s running perfectly now.

  • Brie Clayton

    March 20, 2024 at 2:19 pm

    Thanks for solving this, Julian!

We use anonymous cookies to give you the best experience we can.
Our Privacy policy | GDPR Policy