关于removeFromParent

removeFromParent一直以来,像是2dx以前留下来的产物。在creator中,个人认为不建议用此接口。
如果你想节点不再使用,一般来说就用node.destroy(); 如果你想接口从父节点移除并再次使用,那么就用node.parent = null。

removeFromParent()和removeFromParent(false)并不是简单的和上面两个相等。如果你认为removeFromParent()会把节点destroy,那就错了。
所以我一般在项目中都会替换掉removeFromParent的行为,保证在removeFromParent()时,节点一定会被destroy()。
插件脚本中加入如下代码

cc.Node.removeChild = function (child, cleanup) {
    child.parent = null;
    if(cleanup == true || cleanup == null) {
        child.destroy();
    }
};

cc.Node.removeAllChildren = function(cleanup) {
    if(cleanup == true || cleanup == null) {
        var children = this.children;
        for(var i = children.length - 1; i >= 0; --i) {
            children[i].parent = null;
        }
    }
    else {
        var children = this.children;
        for(var i = children.length - 1; i >= 0; --i) {
            var child = children[i];
            child.parent = null;
            children[i].destroy();
        }
    }
}

这样之后,removeFromParent()的行为就一定会保证节点和组件被destroy。

另外,建议把引擎中的base-node.js中的函数_onPreDestroy的代码
for (i = 0, len = children.length; i < len; ++i)
改成
for (i = children.length - 1; i >= 0; --i)

哥们,没有找到你说的这个文件。倒是找到了一个 base-node.js。 大概看了下,它是先遍历了children 先destroy 后面才删除数组元素的 应该从0开始也没问题吧?

写错了,确实是base-node.js

理论上有问题,但实际上并未发现有问题。
因为parent = null调用时,会从父的children中移除,而这时若刚好在for循环,就会有问题。

就是它children数组没有清理干净而已 真正的 Node 应该已经destroy了,children数组没清干净。