actionscript-3if-statementflash-cs6stageaddchild

AddChild to the stage only once when revisiting frame


I have two frames.

In the first frame you can click a button to go to the next frame. In the first frame I want to add menu1 to the stage just once. If we go to the next frame and then back to the first frame, the menu1 should not be created again since it is already on the stage.

My problem is, when I go back from frame 2 to frame 1, it keeps adding menu1 copies to the stage.

Here is my current code:

stop();

import flash.display.Loader;
import flash.events.MouseEvent;
import flash.net.URLRequest;
import flash.display.Stage;

var menu1:Loader = new Loader();
var request1:URLRequest = new URLRequest ("MENU1.swf");
menu1.load(request1);

if (stage.contains(menu1)){

}
else 
{
    addChild(menu1);
}

Solution

  • The reason it still keeps adding the menu every time, is because your if condition will always be false.

    There are two lines to point out why that is the case:

    var menu1:Loader = new Loader();
    

    In the above line, you are creating a brand new Loader() object and assigning it to the var menu1

    if (stage.contains(menu1)){
    

    in the above line, you're checking if menu1 is currently on the stage

    Since the first line runs every time you visit this frame, a brand new object is created every time. That new object doesn't exist on the stage yet (the previous one does) so the if conditional will always evaluate as false.

    To remedy this, you can do the following:

    var menu1:Loader; //just define the var here, don't assign anything yet
    
    //if menu1 doesn't have a value
    if(!menu1){
    
        //create a new Loader only if one doesn't exist yet
        menu1 = new Loader();
        var request1:URLRequest = new URLRequest ("MENU1.swf");
        menu1.load(request1);
        addChild(menu1);
    }