ForumsProgramming ForumIssue with removeChild

3 4535
Perditus
offline
Perditus
8 posts
Nomad

Here's the code i have:

function clickHandle(e:MouseEvent):void {
container.addChild(beam);
beam.x = 400;
beam.y = 250;

var marker:uint = getTimer();
var lagTime:uint = 1000;
addEventListener(Event.ENTER_FRAME, delay);
function delay(e:Event):void{
if(getTimer() - marker > lagTime){
marker = getTimer();
container.removeChild(beam);
}
}
}

it adds the movieclip beam in container when the mouse is clicked. 1 second later it's supposed to then remove beam. But when i test it i get this in the output:

ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display:isplayObjectContainer/removeChild()
at Function/<anonymous>()

Could anyone tell me how to fix this?

  • 3 Replies
driejen
offline
driejen
486 posts
Nomad

I think your problem is, once your beam has been removed from the container, your ENTER_FRAME function still continues to call your delay function and tries to remove beam from container (even though it no longer exists there.

The solution is to add an extra line that removes your event listener like so;

function delay(e:Event):void{
if(getTimer() - marker > lagTime){
marker = getTimer();
container.removeChild(beam);
removeEventListener(Event.ENTER_FRAME, delay);
}
}
driejen
offline
driejen
486 posts
Nomad

Oh, and if you are having problems with clicking too fast, you can make it so that the body of your clickHandle function is wrapped inside;
if(!container.contains(beam)){
That way you don't end up running the code again while the delay function is still running, which will cause more errors.

Perditus
offline
Perditus
8 posts
Nomad

Thank you driejen, removing the event listener solved the problem and the tip in your 2nd post was also very useful.

Showing 1-3 of 3