Search code examples
arraysactionscript-3removechild

How to remove a child created by an array in ActionScript 3.0


In one of my frames I place an array of a movieclip with random frames of the movieclip showing. After placing the movieclips with a certain frame, it gets spliced from the array. At frame 45 I want to get rid of the created instances but everything I tried with cats.removeChild or variations thereof doesn't seem to work. Does anybody know how to get rid of the created instances?

    function Codetest():void {
        var cardlist:Array = new Array();
        for(var i:uint=0;i<4*1;i++) {
            cardlist.push(i);
        }

        for(var x:uint=0;x<4;x++) {
            for(var y:uint=0;y<1;y++) {
                var c:cats = new cats();
                c.x = x*450+105;
                c.y = y*550+300;
                var r:uint = Math.floor(Math.random()*cardlist.length);
                c.cardface = cardlist[r];
                cardlist.splice(r,1);
                c.gotoAndStop(c.cardface+1);

                addChild(c); // show the card
            }

        }

}


Solution

  • You need to store your created movieclips somehow, for example in another array:

    // this variable should be outside of your function so it will be still available at frame 45. Variables declared inside the function are only accessible from that function
    var cardsArray:Array = []; // same as new Array() but a bit faster :)
    
    function Codetest():void {
        var cardlist:Array = new Array();
        for(var i:uint=0;i<4*1;i++) {
            cardlist.push(i);
        }
    
        for(var x:uint=0;x<4;x++) {
            for(var y:uint=0;y<1;y++) {
                var c:cats = new cats();
                c.x = x*450+105;
                c.y = y*550+300;
                var r:uint = Math.floor(Math.random()*cardlist.length);
                c.cardface = cardlist[r];
                cardlist.splice(r,1);
                c.gotoAndStop(c.cardface+1);
    
                addChild(c); // show the card
    
                // push the new card movieclip into our fancy array
                cardsArray.push(c);
            }
        }
    }
    

    On frame 45:

    // loop trough our movieclips and remove them from stage
    for(var i:uint=0; i < cardsArray.length; i++) 
    {
        removeChild(cardsArray[i]);
    }
    
    // clear the array so the garbage collector can get rid of the movieclip instances and free up the memory
    cardsArray = [];