user2669451
user2669451

Reputation: 11

remove this child and add new child AS3

i've been stuck on this for quite a while, i'm working with a Main.as and LivrmScreen.as and basically LivrmScreen.as is a game screen with other movieclip actions going on... then i have a button on LivrmScreen that i wish to remove LivrmScreen itself and show homeScreen (all the homeScreen functions are in Main.as)

var homeScreen: HomeScreen;
public function LivrmScreen() {

        backhomeBtn.addEventListener(MouseEvent.CLICK, onBackhomeBtnClicked);

    }
function onBackhomeBtnClicked(evt:MouseEvent) {

        homeScreen = new HomeScreen();


        stage.addChild(homeScreen);
        parent.removeChild(this);

    }

this is what i have right now, i added parent.removeChild because it won't remove when it is just removeChild ... and because of that i added stage.addChild so that home screen will show up properly.

but then when homeScreen shows up the button's don't actually work ... so its just showing a dead movieclip. why is that???

i also tried to put the onBackhomeBtnClicked function in main.as thinking so that all the homeScreen functions are there and maybe the buttons will work... but in that case i cant even get the screens to remove and add properly

Upvotes: 1

Views: 961

Answers (1)

Creative Magic
Creative Magic

Reputation: 3141

There's a flaw in your code logics. I don't want to go too deep into the OOP principles or tell you to use frameworks that takes care of these kind of things.

Here's a cheap and fast way out:

in Main.as

private function goToLivrScreen(e:Event = null):void
{
    var livrScreen:LivrScreen = new LivrScreen();
    livrScreen.addEventListener("onClose", onLivrScreenClose);
    addChild(livrScreen);
}
private function onLivrScreenClose(e:Event = null):void
{
    removeChild(e.currentTarget as DisplayObject);
    // add code to show main menu or whatever you wanted
}

in LivrScreen.as

backhomeBtn.addEventListener(MouseEvent.CLICK, onBackhomeBtnClicked);

and handler

private function onBackhomeBtnClicked(evt:MouseEvent):void
{
    // remove all listeners from all object that you have so your LivrScreen could be garbage collected
    // when done just dispatch the Event that Main.as is waiting for
    dispatchEvent(new Event("onClose"));
}

This is a pretty crude way to do it and there can be many improvements, but it will make your code a little cleaner and hopefully, more scalable in case you want to add new screen or change some implementation.

Upvotes: 1

Related Questions