Search code examples
after-effects

After Effects Expression (if layer is a CompItem)


I am trying to make slight modification at line 5 of below After Effects expression. Line 5 checks if the layer is visible and active but I have tried to add an extra check that the layer should not be a comp item. (In my project, layers are either text or image layer and I beileve an image layer means a comp item). Somehow the 'instanceof' method to ensure that layer should not be a comp item is not working. Please advise how to fix this error, thanks.

   txt = "";
   for (i = 1; i <= thisComp.numLayers; i++){
      if (i == index) continue;
         L = thisComp.layer(i);
           if ((L.hasVideo && L.active) && !(thisComp.layer(i) instanceof CompItem)){
          txt = i + " / " + thisComp.numLayers + " / " + L.text.sourceText.split(" ").length;
       break;
       }
    }
    txt

Solution

  • While compItem is available only in ExtendScript, you can actually check the properties available in the {my_layer}.source object.

    Here's a working example (AE CC2018, CC2019 & CC2020): layer_is_comp.aep

    The expression would be something similar to:

    function isComp (layer)
    {
      try
      {
        /*
        - used for when the layer doesn't have a ['source'] key or layer.source doesn't have a ['numLayers'] key
        - ['numLayers'] is an object key available only for comp objects so it's ok to check against it
        - if ['numLayers'] is not found the expression will throw an error hence the try-catch
        */
        if (layer.source.numLayers) return true;
        else return false;
      }
      catch (e)
      {
        return false;
      }
    }
    
    try
    {
      // prevent an error when no layer is selected
      isComp(effect("Layer Control")(1)) ? 'yes' : 'no';
    }
    catch (e)
    {
      'please select a layer';
    }
    

    For your second question, you can check if a layer is a TextLayer by verifying that it has the text.sourceText property.

    Example:

    function isTextLayer (layer)
    {
      try
      {
        /*
        - prevent an expression error if the ['text'] object property is not found
        */
        var dummyVar = layer.text.sourceText;
    
        return true;
      }
      catch (e)
      {
        return false;
      }
    }