Search code examples
actionscript-3flash

How to remove the child inside movieclip


I have a MovieClip on stage named scenePage, and a MovieClip named char_panel which consists of character MCs. One of these is the char1_mc.

When I clicked on char1_mc, this create a new instance(newChar), adding a child in scenePage. I also have a button named btn_remove on stage that should removes the newChar on scenePage when clicked. The problem is, the child(newChar) inside the scenePage does not removes when I clicked the button.

I tried using

scenePage.removeChild(newChar);

But it gives me an error saying, "Parameter child must non-null." Is there any other way to access the instance inside the scenePage? I really need to have access on the child on scenePage.

Here's the script inside char_panel where the char1_mc is, character1 is the class name of char1_mc after I exported it for AS3:

import flash.display.MovieClip;

var newChar: MovieClip;

char1_mc.addEventListener(MouseEvent.CLICK, showChar1);
function showChar1(e:MouseEvent):void
{
    newChar = new character1();
    newChar.height = 215;
    newChar.width = 220;
    newChar.x = 20;
    newChar.y = 202.60;
    MovieClip(root).scenePage.addChild(newChar);
}

And this is the script for btn_remove which is in the main timeline.

btn_remove.addEventListener(MouseEvent.CLICK, remove_character);
function remove_character(e:MouseEvent):void
{
    scenePage.removeChild(newChar);
}

Thanks in advance :)


Solution

  • Your issue is one of scope.

    The main timeline and your char_panel have different scopes. This means vars in one are not available in the other.

    To get to newChar from the main timeline, you'll have to drill down to the appropriate scope.

    Let's assume char_panel is the instance name of an object on the main timeline. If so, you'd have to do this on your main timeline code:

    scenePage.removeChild(char_panel.newChar);
    

    Which is saying "remove the newChar object that is part of the char_panel scope"