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)