ActionScript 3 Understanding the "Error 1009: Cannot access a property or method of a null object reference" Invalidated reference to a frame-based object

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Sometimes gotoAndStop() is called in the middle of the code that refers some frame-based properties. But, right after the frame is changed all links to properties that existed on the current frame are invalidated, so any processing that involves them should be immediately terminated.

There are two general scenarios of such processing to occur: First, a loop doesn't end after gotoAndStop() call, like here:

for each (bullet in bullets) {
    if (player.hitTestObject(bullet)) gotoAndStop("gameOver");
}

Here, a 1009 error means that the player MC was destroyed while processing gotoAndStop() call, but the loop continues, and refers the now-null link to get hitTestObject() from. If the condition would say if (bullet.hitTestObject(player)) instead, the error would be #2007 "Parameter hitTestObject must not be null". The solution is to put a return statement right after calling gotoAndStop().

Second case is multiple event listeners on the same event. Like this:

stage.addEventListener(Event.ENTER_FRAME,func1);
stage.addEventListener(Event.ENTER_FRAME,func2);
function func1(e:Event):void {
    if (condition()) {
        gotoAndStop(2);
    }
}

Here, if condition() is true, the first listener would perform gotoAndStop(), but the second listener would still be executed, and if that one references objects on the frame, a 1009 error will be thrown. The solution is to avoid multiple listeners on a single event, in a single object, it's better to have one listener that handles all situations on that event and can properly terminate if a frame change is needed.



Got any ActionScript 3 Question?