Remove Child and AS3 2025 Error

故事扮演 提交于 2019-11-29 18:06:24

Take a look on the definition of removeChild() :

Removes the specified child DisplayObject instance from the child list of the DisplayObjectContainer instance.

So to get that function executed successfully, it should be executed on the DisplayObjectContainer parent of the child ( DisplayObject ) which we will remove, but if we are outside this parent, the compiler will take the current DisplayObjectContainer as the parent, take this example to understand more :

trace(this);    // gives : [object MainTimeline]

var parent_1:MovieClip = new MovieClip()
    addChild(parent_1);             
    // add the parent_1 to the MainTimeline

var child_1:MovieClip = new MovieClip()
    addChild(child_1);              
    // add the child_1 to the MainTimeline

var child_2:MovieClip = new MovieClip()
    parent_1.addChild(child_2);     
    // add the child_2 to parent_1 which is a child of the MainTimeline         

removeChild(child_1);               
// remove child_1 from the MainTimeline : OK

try {
    removeChild(child_2);           
    // remove child_2 from the MainTimeline : ERROR
} catch(e:*){
    trace(e);                       
    // gives : ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
}

Here we know that child_2 is not a child of the MainTimeline and that's why we got the Error #2025 because the supplied DisplayObject ( child_2 ) is not a child of the caller ( the MainTimeline ).

So to remove the child_2 MovieClip, we have to call removeChild() from it's parent which is parent_1 :

parent_1.removeChild(child_2); // OK

And to simplify or if we don't know it's parent, you can write it :

child_2.parent.removeChild(child_2);

Hope that can help.

Try this

for (var index:int= bArray2.length - 1; index >= 0; --index) {
    bullet2 = bArray2[index];

    // you don't even need this check 
    // if you are not setting elements to null in the array
    if (!bullet2) {
        bArray2.splice(index, 1);
        continue;
    }

    // move the bullet
    if (bullet2.x < 500) {
        bullet2.x += 3;  
    } 

    // if the bullet hit the boss or is out of screen remove it
    if((boss && boss.hitTestObject(bullet2)) || bullet2.x > 500) {
        if (this.contains(bullet2)) {  
            removeChild(bullet2);
        }
        bLives -= 1;
        bArray2.splice(index, 1);
    }
}

Iterating over an array from front to back and removing elements will shrink the array and on the next iteration you will skip elements. It is better to iterate from the back to front and remove.

Also it is a good idea to check if a DisplayObjectContainer actually contains the element you are removing before calling removeChild.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!