ActionScript 3 Understanding the "Error 1009: Cannot access a property or method of a null object reference" Forgotten event listener


function moveChild(e:Event):void {
    if (childMC.x>1000) {

This example will move the childMC (added to Main at design time) but will instantly throw a 1009 as soon as gotoAndStop() is invoked, if that childMC does not exist on frame 2. The primary reason for this is that whenever a playhead passes a key frame (a frame which doesn't inherit the previous frame's object set), either by using gotoAndStop(), gotoAndPlay() with destination frame being separated from the current frame by a keyframe, or by normal play if the SWF is an animation, the current frame's contents are destroyed and the new contents are created using the data stored from GUI. So, if the new frame does not have a child named childMC, the property request will return null and 1009 will be thrown.

The same principle applies if you add two event listeners, but remove only one, or add a listener to one object, but try removing from another. The removeEventListener call won't warn you if the object did not have a respective event listener attached, so read the code that adds and removes event listeners carefully.

Note also: Using Timer objects, calling setInterval() and setTimeout() also creates event listeners, and these should also be cleared properly.