cocos creator 中节点池中的坑

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

好了,这一次是正常的从节点池中取得了节点数据,记录一下 

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值