PDA

View Full Version : RemoveChild, only if it exists?


Pipan
10-28-2007, 12:07 AM
When I create an instance from a class, lets say like this:

circle = new Circle("blue");:
box.addChild(circle);

and later want to replace the blue circle with a green, how can I do?

I mean the application doesnt always know if a circle have been added
or not before.

So if I try this:

box.removeChild(circle);

circle = new Circle("green");:
box.addChild(circle);

...I get an error if there was no circle-instnce there allready.

So how do I solve this?
Thanks.

lucas_wallsi
10-28-2007, 11:06 AM
I am just thinking out loud here. But I am pretty sure the following should work.

box.getChildIndex(circle);

If the circle isn't a child of the box it will throw an error which you could catch. That way you would know whether or not it is a child in the box display list. If it is there it will return the depth which it is at on the display list of box.

Check out the Actionscript 3 Documentation on the DisplayObjectContainer class and its methods for getting children from a display list.

panel
10-28-2007, 01:15 PM
You can't remove object from box display list becouse it take some time to add circle to box dispaly list (this object isn't added yet)

box.addChild(circle);
box.removeChild(circle);


You can play with ADDED_TO_STAGE/REMOVED_FROM_STAGE events

or as @lucas_wallsi sugester use try/catch

try
{
box.removeChild(circle)
}
catch(err:Error)
{

}

wblair8689
06-19-2008, 03:44 PM
http://www.actionscript.org/forums/archive/index.php3/t-122685.html

has clever ..

if(displayObject.contains(myObject)){
displayObject.removeChild(myObject);
}