Search code examples
actionscript-3dynamicinstances

AS 3.0 Dynamic Instance Names


Hi i made a custom class where i would like to create x instances of a movieclip. But the following doesn't work:

package {

import flash.display.MovieClip;
public class CustomClass extends MovieClip {

    public function CustomClass(amount:uint) {  
        var Collector:Array = new Array(); 

        //Add and position Tiles to stage.
        for (var i:uint = 1; i <= amount; i++){ 
            var newMovieClip:MovieClip = new MovieClip;
            newMovieClip.y = amount * 10;
            Collector.push(newMovieClip); 
        }
        addChild(Collector);
    }
}

}

I would like to position them on the timeline with

var customClass_mc:CustomClass = new CustomClass(10);
addChild(customClass_mc);

//try to trace the x position of one of the instances. 
trace(customClass_mc.Collector[5].x);

I keep getting the error: Scene 1, Layer 'Layer 1', Frame 1, Line 5 1119: Access of possibly undefined property Collector through a reference with static type CustomClass.


Solution

  • I found another answer myself which i think is even better!

    You don't need the container at all.

    when you use the following

    package {
    
        import flash.display.MovieClip;
        public class CustomClass extends MovieClip {
    
            public function CustomClass(amount:uint) {  
    
                //Add and position Tiles to stage.
                for (var i:uint = 1; i <= amount; i++){ 
                    var newMovieClip:MovieClip = new MovieClip;
                    newMovieClip.y = amount * 10;
                    newMovieClip.name = "clip"+i;
                    addChild(newMovieClip); 
                }
            }
        }
    }
    

    No i can acces the movieclips by using:

    var customClass_mc:CustomClass = new CustomClass(10);
    addChild(customClass_mc);
    
    //try to trace the x position of the fifth instance. 
    trace(customClass_mc.getChildByName("child5").y);