0
votes

I have a main swf that loads other swfs. Everything works correctly with the code below that is inside the main swf (sketch):

var loader:Loader = new Loader();
stage.addChild(loader);
loader.load(new URLRequest('external.swf'));

However, when trying to load an external swf that uses a document class, it had an access error to the stage object. To be clearer, a document class is configured in the swf publication that will be loaded:

Classe de documento Main

Inside the Main.as, have the class for the access code to the stage:

package {
    import flash.display.MovieClip;
    public class Main extends MovieClip {
        public function Main() {
            // access stage
            trace(stage);
            trace(stage.stageWidth);
        }
    }
}

When the main swf tries to load the external swf, the error occurs:

null
TypeError: Error #1009: Cannot access a property or method of a null object reference.

How to solve this problem?

1

1 Answers

1
votes

Don't reference stage in constructor of a loaded swf. Subscribe to Event.ADDED_TO_STAGE instead.

package {
    import flash.display.MovieClip;
    public class Main extends MovieClip {
        public function Main() {
            trace("1 stage="+stage); // null, if this swf is loaded
            addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
        }
        protected function onAddedToStage(event:Event):void
        {
            trace("2 stage="+stage); // object
        }           
    }
}

UPDATE: In case you can't modify the loaded swf, you can override its main class definition in your loader swf. This may yield undesired consequences if the loaded swf's Main class contains important and/or ever-changing logic.

  1. define Main class in you loader swf in the same package you have it in in your loaded swf.
  2. write proper actions with ADDED_TO_STAGE in Main constructor to access stage correctly.
  3. make this Main compile into your loader swf: just add Main; in you main swf's code somewhere (this can also be done with compiler argument in flash builder, but why bother).

This way you replace the definition of Main completely.