cocos creator中节点池中的put方法:默认在执行该方法的时候自动从父节点中移除该节点所以父节点的子节点数量会发生变化:
/**
* @en Put a new Node into the pool.
* It will automatically remove the node from its parent without cleanup.
* It will also invoke unuse method of the poolHandlerComp if exist.
* @zh 向缓冲池中存入一个不再需要的节点对象。
* 这个函数会自动将目标节点从父节点上移除,但是不会进行 cleanup 操作。
* 这个函数会调用 poolHandlerComp 的 unuse 函数,如果组件和函数都存在的话。
* @example
* let myNode = cc.instantiate(this.template);
* this.myPool.put(myNode);
*/
put(obj: Node): void;
我再游戏中试图重启游戏的时候的进行节点回收,起初我是这样做的:
private restartGame(button: any): void {
this.playerCtrl.begin = false;
// 回收节点池中的数据
for(let i = 0; i < this.node.children.length; i++) {
// put操作自动从父节点上移除该节点所以this.node.children.length是变化的
this.pool.put(this.node.children[i]);
}
// while(this.node.children.length > 0) {
// this.pool.put(this.node.children[this.node.children.length - 1]);
// }
// 恢复一些初始好的数据
this.curState = GameState.GS_INIT;
this._curState = GameState.GS_INIT;
}
事实证明我再重新从节点池中去取节点的时候发现节点池没有东西,原因就是犯了低级的错误,this.node.children.length是变化的,这样就会错误回收节点:所以正确的姿势应该是:
private restartGame(button: any): void {
this.playerCtrl.begin = false;
// 回收节点池中的数据
// for(let i = 0; i < this.node.children.length; i++) {
// // put操作自动从父节点上移除该节点所以this.node.children.length是变化的
// this.pool.put(this.node.children[i]);
// }
while(this.node.children.length > 0) {
this.pool.put(this.node.children[this.node.children.length - 1]);
}
// 恢复一些初始好的数据
this.curState = GameState.GS_INIT;
this._curState = GameState.GS_INIT;
}
好了,这一次是正常的从节点池中取得了节点数据,记录一下