Tuesday, 4 May 2010

Instantiate an SWF as a Class

At the company where I work we add the need to make several SWF that needed to come up, in different timings and according to user navigation. But since we wanted to keep the final application as light as possible, we had the need not to instantiate all the external swf at once.

After some research we found and implemented the following solution: instantiate external swf's as separate classes:

  import flash.display.MovieClip;
  import flash.events.Event;
  import flash.net.URLRequest;
  import flash.display.Loader;
  public class Load extends MovieClip
     var storeLoadedObject:Class; //Self explained ;)
     var loader:Loader;
     public function Load():void{
         loader=new Loader();
         loader.load(new URLRequest("example.swf"));
         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeObjForEdit);

     public function completeObjForEdit(evt:Event):void{
         var className:String="com.gameRoot"; //Document class of loaded file
          storeLoadedObject=loader.contentLoaderInfo.applicationDomain.getDefinition(className) as Class;

     public function makeLotsOfCopies():void{
        for(var i:uint=0; i<20;i++){
           var copy:MovieClip=new storeLoadedObject();

And that's it.