Search code examples
actionscript-3flashflash-cs6uiloader

close / unload UiLoader as3


I'm using a Loader to display a SWF. I have a button to load the SWF and I want that same button to close or hide or unload the SWF.

Here's part of my code:

var so:Boolean = false ;
    glossary.addEventListener(MouseEvent.CLICK, glossaire)
    function glossaire (e:MouseEvent) {
        var myLoader:Loader = new Loader();                     
        var url:URLRequest = new URLRequest("glossary.swf");
        if (so == false )
        {
            so = true ;
            myLoader1.load(url);                                    
            addChild(myLoader);
        }
        else{  
            so = false ;
            //i tried  
            myUILoader.unload(); 
            removeChild(myUILoader);
            // but my loader still appear in the stage how can remove or hide it
        }
    }

Solution

  • Your issue is that your loader is scoped to the click function, and that you are creating a new Loader every click (when really you only want to create a new loader on the first click). Also, you seem to be confused on what your loader is called as you have references to myLoader, myLoader1 and myUILoader.

    //put the loader var out of the function scope here (so it persists after the function finishes). 
    var myLoader:Loader;
    
    glossary.addEventListener(MouseEvent.CLICK, glossaire);
    
    function glossaire (e:MouseEvent){
    
        //instead of using the so boolean, just check if loader is null
        if (myLoader == null){
            myLoader = new Loader();
            myLoader.load(new URLRequest("glossary.swf"));                                    
            addChild(myLoader);
        }else{
            myLoader.unloadAndStop(); 
            removeChild(myLoader);
            myLoader = null; //set it to null now that it's been removed, so the next time this click function runs, a new loader will be made
        }
    }
    

    If you just wanted to hide the loaded swf (instead of completely unloading it), you could do this:

    function glossaire (e:MouseEvent){
        //create the loader and load if it hasn't been done yet
        if (myLoader == null){
            myLoader = new Loader();
            myLoader.load(new URLRequest("glossary.swf"));                                    
        }
    
        //the parent property of the loader will be null if it hasn't been added (or has been removed) via addChild/removeChild
        if(myLoader.parent != null){
            removeChild(myLoader);
        }else{
            addChild(myLoader);
        }
    }