Creating MovieClips dynamically at run-time using the Linkage Class

linkageI found myself needing to create a MovieClip dynamically at run-time. But all I had was a string representation of its Class, as set in the Linkage properties for the Symbol. In my situation the string had been stored in an xml file. Now you could use a standard switch/case block to do this, checking the string and creating a new MovieClip as required. But in this case there were hundreds of possible things it could have been, and it seemed a very “hacky” way to do it.

So how do you go about creating an actual display object from just the Linkage Class value? Thankfully it’s pretty easy, and this new bit of code now sits happily in my “everyday functions” collection!

Edit: Updated to be a little more robust, and removed an un-needed cast:

public function createMovieClipFromLinkageValue(linkageValue:String):MovieClip
var libraryReference:Class = getDefinitionByName(linkageValue) as Class;
catch (error:ReferenceError)

if (libraryReference)
return new libraryReference();

return new MovieClip;

var newClip:MovieClip = createMovieClipFromLinkageValue(“playerFishMC”);

Make sure you have imported flash.utils.getDefinitionByName.

Simply pass this function the Linkage value as entered in the IDE, and it’ll spit a MovieClip back at you (providing it was a MovieClip in the first place). I’m sure you can see how to extend it to return a Sprite instead, should you require that.

Posted on September 15th 2009 at 12:58 pm by .
View more posts in Tutorials. Follow responses via the RSS 2.0 feed.

6 Responses

Leave a comment
  • September 15th 2009 at 3:17 pm

    Wow.. nice and simple! I’ve often encountered this or similar problems but hadn’t had a big enough case to bother figuring this out yet. I was familiar with how to do similar things with Ruby and was assuming there had to be something like this too for actionscript. Glad there is. Thanks for putting this together.. I’m totally snagging it and adding it to my utils class as well. :)

  • September 15th 2009 at 3:40 pm

    I think you have an extra step in there. Doesn’t libraryReference == sourceClass?

  • September 15th 2009 at 4:01 pm

    Josh: Yes. I found an issue in my project where some of the linkage strings hadn’t been stored correctly, so I’ve updated the code above to count for this (returns an empty movieclip if the class doesn’t exist), and removed the un-needed object cast you were referring to.

  • September 16th 2009 at 1:15 pm

    Nice one! I’ve modified it slightly so it works on library Sound items too. It’s now an essential part of my core utils. Cheers!

  • March 23rd 2010 at 2:15 pm

    WOW really great
    I used much harder methods to duplicate mclips

Make yourself heard