Adam Bieńkowski
Adam Bieńkowski

Reputation: 585

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
}
...

Upvotes: 3

Views: 74

Answers (2)

Jason Reeves
Jason Reeves

Reputation: 1716

this will consolidate what you showed above:

function addChildOfType(type:Class):void{
    var mc:type = new type();
    stage.addChild(mc);
}

to use this just call:

addChildOfType(Clip1);
addChildOfType(Clip2);
addChildOfType(Clip3);

EDIT:

if your library is an externally loaded swf, then @M. Laing is correct in how to get them. If your library is your flash library in the same flash file, then this answer will fix you up.

Upvotes: 1

M. Laing
M. Laing

Reputation: 1617

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/

Upvotes: 5

Related Questions