对象池简单创建和管理

//创建对象池
    getBulletPool(node) {
        this.bulletPool = new cc.NodePool();
        let initCount = 5;
        for (let i = 0; i < initCount; ++i) {
            let bulletItem = cc.instantiate(node); // 创建节点
            this.bulletPool.put(bulletItem); // 通过 put 接口放入对象池
        }
    },
    //生成对象
    createBullet(parentNode,node) {
        if(cc.playstatus){
            let bulletItem = null;
            if (this.bulletPool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
                bulletItem = this.bulletPool.get();
            } else { // 如果没有空闲对象,也就是对象池中备用对象不够时,我们就用 cc.instantiate 重新创建
                bulletItem = cc.instantiate(node);
            }
            bulletItem.parent = parentNode; // 将生成的敌人加入节点树
            //接下来就可以调用 node 身上的脚本进行初始化
            bulletItem.getComponent('bullet').init();
        }
    },
    //回收
    onBulletKilled(enemy) {
        // enemy 应该是一个 cc.Node
        // 和初始化时的方法一样,将节点放进对象池,这个方法会同时调用节点的 removeFromParent
        this.bulletPool.put(enemy); 
    },
    //清空
    destroyPool(enemy) {
        this.bulletPool.clear();
    },
    //生成新的对象
    getNewbullet(parentNode) {
        this.createBullet(parentNode,node);
        this.schedule(()=>{
            console.log('此时对象池数量====',this.bulletPool.size());
            this.createBullet(parentNode,node);
        },0.2);
    },
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容