简体   繁体   中英

Cannot access a property or method of a null object reference

I try to do preloder in Flex for my project written in Flash. I make this with the help of this site link text My Flash project have next source in main class called Game

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);

private function keyDown(event:KeyboardEvent) {
   if (event.keyCode == 81 && q_was_push == false) q_was_push = true;
   if (event.keyCode == 81) press_q = true;
   if (event.keyCode == 65) press_a = true;
   if (event.keyCode == 83) press_s = true;
   if (event.keyCode == 32) press_space = true;
} ...

When I take new swf file maked by Flex, I have error TypeError: Error #1009: Cannot access a property or method of a null object reference. at Game()

if I comment

//stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
//stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);

Flex application work but Flash application does not react to button presses

Please how I can make preloader and work buttons together

The stage property will be null until a display object is added to the display list. Listen to the addedToStage event and add the key listeners from there.

addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
function onAddedToStage(e:Event):void
{
    stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
    stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
}

Anytime you need access to the stage, have the Class listen for it/check for it in the constructor, and have your init function be the handler.

package
{
    import flash.display.Sprite;
    import flash.events.Event;
    /**
     * ...
     * @author Brian Hodge
     */
    public class SomeClass extends Sprite
    {

        public function SomeClass() 
        {
            if (stage) _init();
            else addEventListener(Event.ADDED_TO_STAGE, _init);
        }
        private function _init(e:Event = null):void
        {
            //You may now access the stage property of the DisplayObject.
            stage.addEventListener(Event.RESIZE);
        }
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM