Actionscript 3: Reference to Stage is Null

While writing a custom Class in Actionscript 3 today I came across an issue that took me a little bit to figure out where the compile error was coming from. I was getting the wonderful error:

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

After a bit of troubleshooting I discovered that a reference to the stage in my Class was returning null. I did some research and found that the stage is really a DisplayObject’s reference to the stage DisplayObject.stage. However, if that DisplayObject is not yet added to the stage, the stage of the DisplayObject is not instantiated yet and returns a null value. In my case, the class was a Sprite I was adding to the stage at runtime.

I then discovered that my Class shouldn’t get initialized until it was fully added to the stage since I had calls to the the stage class such as stage listeners and stage properties. I then determined that it was essential to add an event listener for my Sprite to be added to the stage:

public functionmyClass()
         addEventListener(Event.ADDED_TO_STAGE, init);

Once the Object is added to the stage, you can initialize the rest of the Class. This was an easy fix to the issue that I hope others find useful.

  • Steven Loe

    Nice explanation how stage references come to be for classes that extend the DisplayObject.

    -Steven Loe

  • GraphNickDesign

    Thanks Steven.

    The same applies to any parent reference of the DisplayObject such as MovieClip(parent). You must listen for that object to be added to the stage of parent DisplayObject.