Search code examples
actionscript-3flashloadmovieclipflashdevelop

AS3 Load swf As Movieclip


I need to load in an external swf and be able to use it as a Movieclip in FlashDevelop i.e I need to be able to go to specific keyframes, start and stop it playing etc. Some simple working sample code would be hugely appreciated as I cannot find any satisfactory tutorials through Google.

EDIT I now have this code

package 
{
import flash.net.*;
import flash.display.*;
import flash.events.*;
import flash.utils.getQualifiedClassName;

public class Main extends MovieClip 
{

    var animatedBox:MovieClip = new MovieClip();
    var ldr:Loader = new Loader();
    var frames:int = 0;

    public function Main():void 
    {
        if (stage) init();
        else addEventListener(Event.ADDED_TO_STAGE, init);
    }

    private function init(e:Event = null):void 
    {
        removeEventListener(Event.ADDED_TO_STAGE, init);
        ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, onload);
        ldr.load(new URLRequest("../lib/test.swf"));
    }

    function onload(e:Event)
    {
        if ( !e.target )
        return;

        if( e.target.content is MovieClip )
        {
            animatedBox = e.target.content as MovieClip;

            animatedBox.gotoAndPlay("Start");
        }
        else
        {
            trace( getQualifiedClassName( e.target.content ) );
        }
    }

}

}

After I try to run it I get [Fault] exception, information=TypeError: Error #1009: Cannot access a property or method of a null object reference. Any ideas?


Solution

  • import flash.utils.getQualifiedClassName;
    
    var mc: MovieClip;
    
    var ldr: Loader = new Loader();
    ldr.contentLoaderInfo.addEventListener( Event.COMPLETE, onLoad );
    ldr.load( new URLRequest("your.swf") );
    
    
    function onLoad( e:Event ):void 
    {
        if( !e.target )
            return;
    
        trace( getQualifiedClassName( e.target.content ) );
        /* if you get: flash.display::AVM1Movie
           it means you are trying to load an AS1 or AS2 SWF
           into AS3 SWF. They both need to be AS3 */
    
        mc = e.target.content as MovieClip;
        mc.gotoAndPlay( 2 );    
        // or  mc.gotoAndPlay( 'yourLabel' ); 
    
    }