removeChild method not working as I would have thought

Subscribe to removeChild method not working as I would have thought 5 posts

Sign in to reply


 
avatar for SumYungGai SumYungGai 342 posts
Flag Post

I’m new to AS3 and have been making a Snake game. I’ve come up with a problem with the code (Yes, I have magically created problems trying to program Snake…It’s going to be a long day).

Anywho…My problem is, with removeChild…I’m getting strange errors being throw at me. Not only that, but my Movieclip (myFood) is not being removed entirely, only the visuals of it are.

That being said, here is, what I believe to be, the most important chunk of code for this problem, along with the error it gives me.

/*
 * Code for the Snake and whatnot extras.
 * Also, Snake and Food are classes.
 */

var myFood:Food = new Food();
stage.addChild(myFood);

function snakeEatFood() {
    if (mySnake.x == myFood.x && mySnake.y == myFood.y) {
        stage.removeChild(myFood);
        makeNewFood();
    }
}

function makeNewFood() {
    var myFood:Food = new Food();
    stage.addChild(myFood);
    //Also I have in here a code to move the food to a certain spot...but that works
    //perfectly, and so I have not included it
}

Error:

ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
    at flash.display::DisplayObjectContainer/removeChild()
    at AS3Snake_fla::MainTimeline/snakeEatFood()
    at AS3Snake_fla::MainTimeline/myEnterFrame()

Is there a better method for this, as there was in AS2?

 
avatar for Jabor Jabor 11382 posts
Flag Post

Not only that, but my Movieclip (myFood) is not being removed entirely, only the visuals of it are.

That’s the way removeChild works, yes.

MovieClips in AS3 act somewhat differently to how they do in AS2. They exist independently of the stage, and you can add or remove them at any time, and reuse them however you want.

The error occurs because you try to remove myFood a second time after you’ve already removed it – but that’s only a symptom of the problem, and not the root cause.

Your problem is primarily one of variable scope – the new food you make in your makeNewFood() function is not the same one you refer to elsewhere.

Change this line:

var myFood:Food = new Food();

to:

myFood = new Food();

and everything should resolve itself.

 
avatar for SumYungGai SumYungGai 342 posts
Flag Post

Ahh…Thank you Jabor.

 
avatar for skyboy skyboy 5921 posts
Flag Post

you should probably just move it instead of making a new movieclip – it’s easier on memory since it’s not deleted until the computer almost runs out of memory (there’s a thread on this somewhere in here)

 
avatar for SumYungGai SumYungGai 342 posts
Flag Post

Ahh yes. That would make more sense wouldn’t it. _ =P Whatev’ At least I have Jabors knowledge for the future. Thanks to both of you.

Sign in to reply