AS3 stage.addChild / stage.removeChild << Must be child of caller

Ric picture Ric · Aug 11, 2011 · Viewed 12.6k times · Source

If im usin function to add a mc to the stage like so:

var myChild:MC= new MC();

function somefunc()
{
   stage.addChild(myMC)
}

but when I try to remove the mc by:

stage.removeChild(myMC)

I get The supplied DisplayObject must be a child of the caller error... any suggestions or work arounds?

Answer

Nathan Smith picture Nathan Smith · Aug 11, 2011

Your code should work if the item is on the stage. Perhaps qualifying it with a conditional statement like so:

if (myMC.stage != null)
   stage.removeChild(myMC);

Alternatively you could use the following code but it is probably not best practice.

if (myMC.parent != null)    
   myMC.parent.removeChild(myMC);