Search code examples
actionscript-3flashmovieclip

How to dynamically add an Object from Library?


I've got in Library few MovieClips and I want to make function which is loading them into stage. My problem is I can not found different solution than making separate functions for every MovieClip. I'm looking for something like that:

function addAnyClip(name){
  //create new object 'name'
  stage.addChild(chosenObject);
  rest of code
}

because it's better than:

function addClip1(){
  var mc1:Clip1 = new Clip1;
  stage.addChild(mc1);
  ///rest of code
}

function addClip2(){
  var mc1:Clip2 = new Clip2;
  stage.addChild(mc2);
  ///rest of code
}

function addClip3(){
  var mc1:Clip3 = new Clip3;
  stage.addChild(mc3);
  ///rest of code
}
...

Solution

  • Look into using getDefinitionByName

    You would do something like the following:

    var mcClass:Class = getDefinitionByName("NameOfClipInLibrary")

    And then just create anew object that is of the class type mcClass

    Here are a couple of links to help explain how to use it... http://www.jesseknowles.com/blog/dynamically_attaching_movieclips_in_as3/

    http://www.emanueleferonato.com/2011/03/31/understanding-as3-getdefinitionbyname-for-all-eval-maniacs/