Search code examples
actionscript-3flash-cs4

Dynamically creating movieclip instances


I use the code below to create 3 movie clips.

var A:Array = new Array();

for (var i:uint = 0; i < 3 ; i++) {
        A[i] = new hayvanSec();
        A[i].x = 240+i*160;
        A[i].y=300;
        addChild(A[i]);
}

I have 10 image files in the library. I want to show one of these images inside those dynamically created movie clips randomly.


Solution

  • In the flash IDE make those image a MovieClip and name your clip with something like that XXX_0, XXX_1,...,XXX_9. Then you can in your function you can get the random reference to your clip with :

    var myImageName:String="XXX_"+Math.floor(Math.random()*10);
    // and then get the movie from the library
    var clazz:Class=ApplicationDomain.currentDomain.getDefinition(myImageName) as Class;
    if (clazz !== null) {
      var mc:MovieClip=MovieClip(new clazz());
      (...).addChild(mc);
    }