Search code examples
actionscript-3loaderdocument-class

AS3 trouble instantiating Document Class of loaded SWF


I am loading one swf into another using the Loader class, but when the child swf finishes loading and is added to the display list, its Document Class is not instantiated. I have a few trace statements that should execute when the object is created, but nothing is happening when loaded into the parent SWF. When I compile the child SWF on its own, the Document Class runs as expected.

So I'm wondering... how do I associate a child SWF's Document Class with Loader.content?

Code updated with a solution from Kishi below.

public class Preloader extends Sprite {
    import flash.net.*;
    import flash.display.*;
    import flash.events.*;

    // code in parent SWF's Document Class (Preloader.as)
    private var swfLoader:Loader;
    public var mainMovie:MovieClip;

    public function Preloader(){   
        swfLoader = new Loader();
        swfLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderDone);
        swfLoader.load(new URLRequest("mainmovie.swf"));
    }

    private function loaderDone(e:Event):void {
        // Cast Loader.content to MovieClip
        mainMovie = MovieClip(swfLoader.content);

        mainMovie.addEventListener(Event.ADDED_TO_STAGE, mainMovieAddedListener);

        addChildAt(mainMovie, 0);

    }
    private function mainMovieAddedListener(e:Event):void {
       // init() not necessary
    }
}

// MainMovie.as runs after casting swfLoader.content to MovieClip

public class MainMovie extends Sprite {

    public function MainMovie(){
        trace('MainMovie WHATTUP'); 
    }

    public function init():void {
        trace('init'); 
    }
}

Cheers!


Solution

  • The problem is how you are trying to access the swf instance.

    First, the document class instance is referred by Loader's content property. You'd reference it like this:

    var swf:DisplayObject = swfLoader.content;
    

    But, even then you'd have to cast the DisplayObject either to it's real class (MainMovie, in this case) or a dynamic class (such as MovieClip), as you are trying to use a custom property, that's not part of DisplayObject itself. Therefore, you could call MainMovie.init() like so:

    var swf:MovieClip = MovieClip(swfLoader.content);
    swf.init();
    

    Hope that helps.