I’m familiar with [FONT=Courier New]Error #1009: Cannot access a property or method of a null object reference[/FONT]. but in this case I’m baffled about how to fix my code so that it still does what I need it to do while not producing the error.
Here’s my very simplified example. I use “addBtn” button to put a movie clip “mc” on the stage (from the library), and a “deleteBtn” to delete mc. Also, with addBtn I start a timer that iterates a var called counter.
mc has some code that looks at counter on the parent and executes a trace statement when counter hits 30. I use an ENTER_FRAME event for mc to listen constantly to the value of counter.
So the code looks like this:
stage/root:
var counter:int;
var timer:Timer = new Timer(100);
timer.addEventListener(TimerEvent.TIMER, iterateCounter);
function iterateCounter(event:TimerEvent):void {
counter++;
counterField.text = counter.toString();
}
var mc = new MC;
// addChild(mc);
addBtn.addEventListener(MouseEvent.CLICK, addMC);
function addMC(event:MouseEvent):void {
addChild(mc);
timer.start();
}
deleteBtn.addEventListener(MouseEvent.CLICK, deleteMC);
function deleteMC(event:MouseEvent):void {
removeChild(mc);
timer.stop();
}
mc has this code:
addEventListener(Event.ENTER_FRAME, mc_listen);
function mc_listen(event:Event):void {
if (event.target.parent.counter == 30) {
trace("counter hit 30");
}
}
Coded this way, I get the following error:
[FONT=Courier New]TypeError: Error #1009: Cannot access a property or method of a null object reference.[/FONT]
[FONT=Courier New]at MC/mc_listen()[/FONT]
The error pops up repeatedly, I assume as a result of the ENTER_FRAME listener perpetrator. Also, the error shows up immediately, not waiting for addBtn to be clicked.
I am able to add mc just fine if I get rid of the buttons and just do an addChild(mc) (by uncommenting the line that’s commented out). But the problem is NOT with the removeChild(mc), which was my initial assumption, because I can comment out the removeChild(mc) and still get the error.
So what’s going on, and what do I need to change? I assume the offending functionality is [FONT=Courier New][COLOR=blue]event.target.parent.[/COLOR]counter[/FONT] but I don’t understand what the problem is, or why it’s a problem when I’m using the buttons, but not when I get rid of the buttons and just do the addChild(mc).
One more thing: The program still works while the error is firing repeatedly – I get the trace. I don’t really understand that either…
Thanks!