Quick Workaround: AS3 gotoAndStop Nasty Bug

Okay, I admit it. I am old-school. I use Flash Pro CS5 as my only Flash development tool. I do all my coding on timelines and I like it that way.

I have been working with AS3 for few months now, and I have to say, I have to write twice the code to actually do what I was able to do using AS2. I miss those good old days.

Anyway, I’ve been developing an AIR Mobile application and hit by this nasty gotoAndStop bug. If you are feeling lazy to click the link and see detailed explanation, here’s a excerpt from the post:

myMC.gotoAndStop('FINISHED_SCREEN');
myMC.result_txt.text = "You won!";


Leading to following error:

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

To clarify: in this context, result_txt is the name of a TextField that exists on the stage, and only exists on the frame with the label "FINISHED_SCREEN". If you haven’t previously displayed this frame, and you run the code above, then sometimes you will find that the result_txt TextField object hasn’t been properly instantiated by Flash yet when the second line is run – therefore myMC.result_txt will resolve to null, and you’ll get the error above.

I tried and found many kind of solutions, but they were more like adding a lot more code and changing the way my jumping from frame to frame works.

So, experimented a little, and ended up with my own solution. It’s kind of dirty one ;)

First you need to Export for ActionScript your problematic MovieClip from Library. Make sure you add text Class at the end of export ID/class name. i.e. my original Library item was named "mcCircle", so I Export it as "mcCircleClass".

Now, on the keyframe where you are getting that null reference error. Initialize your MovieClip as follows:

var mcCircle:mcCircleClass;
if(this.getChildByName("mcCircle") == null)
{
    mcCircle = new mcCircleClass();
addChild(mcCircle); }

After this you can access mcCircle as before. You might have to set it’s properties (x/y etc.) again, as we just created a new instance which doesn’t have values from previous instance. In my case, I just had to set it’s X and Y to position it back where it belonged.

It’s not as optimistic as other solutions, but it does the job when you need to quickly get through it.

I am quite disappointed by Adobe since Timelines are the basics of Flash from the very core. This bug is around since Flash 9 days, and Adobe still haven’t fixed it. Come on Adobe, you can do better!

Update: Some other references to the problem:

// chall3ng3r //