javascriptextendscriptafter-effects

Why are Extendscript objects invalidated when created inside a function?


function addControl(layer, name){
    newCtrl = layer("Effects").addProperty("Slider Control");
    newCtrl.name = name;
    return newCtrl;
}
var Slider1 = addControl(ExistingLayer, "slider 1");
$.write(Slider1.name);
var Slider2 = addControl(ExistingLayer, "slider 2");
$.write(Slider1.name);

Error Code# 45: Object is invalid

Attempting to access Slider1.name after Slider2 is created results in an error as Slider1 is now [Invalid Object]

I feel this has something to do with referencing and garbage collection but as javascript objects should pass as reference and 'addProperty' should create a new object, I don't understand why.

I should add it fails with and without the 'var' keyword


Solution

  • It's because of the terrible API. Once you've added or deleted a property like an effect to a layer, or a layer to a comp, any references to all effects in that layer, or layers in the comp are made invalid. You have to either keep track of all the current effects that are on the layer and refer to them by indexes, or add an identifying property to them, and loop through the available properties matching the identifier. For example, when creating the effect

    newCtrl.identifier = "ctrl"+ id; //where id is a unique string or number
    

    and then you loop through the effects of the layer and look for the identifier

    if (thisEffect.identifier === "ctrl"+ id){
        dostuff()
    }