Linked In Profile 
Posted 12 April 2008
1 Comment

About a week ago I decided to finally give AS3 a real test drive as every other attempt I have made to understand the language has ended up in complete frustration that it doesn’t do things the way I’m used to. I have to say the experience has been painful, but I am beginning to understand (albeit slightly) how to work with classes and objects and all that fancy stuff.

[Warning: Geek-talk ahead]
Today, I ran into a particularly interesting problem. In AS2, any time you referenced Stage…from anywhere, Flash knew what you were talking about. In AS3, it’s not that simple. Sometimes you will want to reference stage from a class that hasn’t yet added anything to the DisplayObject (in other words, you haven’t used any addChild commands yet), and therefore Flash has no clue what the stage is, therefore throwing stage = null.

Why is this important? Say you have an EventListener in one of your classes, and you want to attach this EventListener to the stage so you can detect any time that the mouse button is de-pressed (firing MouseEvent.MOUSE_UP). Well, in this case, you cannot simply say:

stage.addEventListener(MouseEvent.MOUSE_UP, eventHandler);

This will sometimes give you an error that explains that you cannot use a property of a null object reference. Huh? In plain English: “I don’t know where stage is because when I call it, it is null.”

To get over this annoyance, I scoured the web and found this post by Senocular which helped explain what was going on. However, I did not want to create a new class, and I did not want to pass the stage reference directly (because I want this experiment to do things a certain way). Not quite satisfied with my options, I continued searching and found that you can do this instead:

my_sprite.stage.addEventListener(MouseEvent.MOUSE_UP, eventHandler);

Where my_sprite is a direct reference to something on my stage per say. So I’m happy to report that the solution is much simpler than I thought — although if I get in a crunch again, Senocular’s post really helped me understand what was going on.

So how’s my little experiment going? Well, let’s just say that if I had to do it in AS2, it would’ve been done in about 1 hour. So far, I’m going on roughly 15 hours over a four day span. I am ready to throw my computer out the window. :(

[sigh] What can I say? I’m still not sold on all this OOP mumbo-jumbo. ;)

One Response to “Stage = null”

  1. mike Says:

    i hear you man. i’m still resisting the change. ;)