如何删除由 ActionScript 3.0 中的数组创建的子项

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

在我的一个帧中,我放置了一个动画片段数组,其中显示了动画片段的随机帧。放置具有特定帧的动画片段后,它会从数组中拼接。在第 45 帧,我想摆脱创建的实例,但我尝试使用 cats.removeChild 或其变体的所有内容似乎都不起作用。有人知道如何摆脱创建的实例吗?

    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
            }

        }

}

引用 cats 似乎是 class 因此您无法通过 cats 删除 cats 的实例 class(除非这样编码)。您需要做的是清理您添加 children 的容器。

实施:

function clear():void
{
    while (numChildren > 0) removeChildAt(0);
}

用法:

clear();

您需要以某种方式存储您创建的动画片段,例如在另一个数组中:

// 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);
        }
    }
}

第 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 = [];