Search code examples
flashactionscript-3

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


I have two classes: class A and class B. Class A makes a number and passes it to class B.

When I define class A in class B, Flash throws a TypeError:

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

It's a common error in Flash.

I have two functions in class A:

Class A:

public function ClassAConstractor():void{
  stage.addEventListener(MouseEvent.MOUSE_DOWN , OnMouseDown );
  stage.addEventListener(MouseEvent.MOUSE_UP , OnMouseUp);
}

Class B:

mmm = new ClassAConstractor(); // << when i want define class a in b

When I remove those two lines in the constructor function of class A, the problem is solved, but I need those two lines.

This problem shows when I define class A in class B. When I don’t any define class A in class B, there is no problem; it works well.

I know Flash throws error for STAGE, but I don’t know how to solve this problem.


Solution

  • it sounds like you're attempting to access the stage before it's available. use an Event.ADDED_TO_STAGE event.

    package
    {
    //Imports
    import flash.display.Sprite;
    import flash.events.Event;
    
    //Class
    public class MyClass extends Sprite
        {
        //Constructor
        public function MyClass()
            {
            //trace(stage.stageWidth);
            //too early to call the stage, unless MyClass is the Document Class
    
            addEventListener(Event.ADDED_TO_STAGE, init);
            }
    
        //Initialization
        private function init(evt:Event):void
            {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            trace(stage.stageWidth);
            }
        }
    }