Feb 15 2009

AS3 creating movieclips dynamically

Category: ClassesHadi Tavakoli @ 11:43 pm

Today I almost teared myself apart untill I finally found a good solution for creating diffrent instances of a movieclip from the library! or at least I think this is a good method! The best solution I could come up with anyway and I thought to share it with you as I'm sure a lot of people are looking for a good way to dynamically create different instances of a movieclip being exported for ActionScript in the library.

Here is how the FLA is set up. we have a movieclip in the library, and it's checked for export to ActionScript. (Export in Frame 1 is also checked so the movieclip will be initialized automatically at startup) You are most probably aware that if you are using a high speed internet connection such as broadband you are able to load whole clips in one go. This is really useful when you want to watch a movieclip.

I presume that you already know the fact that if a movieclip has been checked for export to AS from the library, Flash will create a class for it blindly, OR you can setup a class for it manually and just locate the path... if not, maybe you would need to read my other post here, read that first and then get back to here.

Alright, imagine that we have set up our movieclip in the library and the path to its class is something like:

com.myFlashlab.classes.tools.hMenu.BoxStyle1

ok, now whenever you want to create multipie copies from that movieclip (Or any other class, you just need to have the full path to the class and it will work) you need to use the "getDefinitionByName" method like this:

var _myStyleClassName:String = com.myFlashlab.classes.tools.hMenu.BoxStyle1; var theClassName:Class = getDefinitionByName(_myStyleClassName) as Class; var theClass:MovieClip = new theClassName(); theClass.name = "box" + i; // i is maybe a variable being used in a loop. theClass.x = i*50; addChild(theClass)

I hope this little post will save you a lot of time and you don't have to look for duplicateMovieClip and attachMovieClip equivelents any more :)

Regards,
Hadi

Tags: , , , , , ,