分享cocos creator对象池poolManager.js直接用

摘要
节点的创建(cc.instantiate)和销毁(node.destroy)操作是非常耗费性能的。如果制作有大量敌人或子弹需要反复生成和被消灭的动作类游戏时,需要使用对象池。

环境
cocos creator 2.4.3
编辑工具HBuild X

像这样的的项目:
子弹,障碍物,敌人都可以使用对象池
file

poolManager.js代码

/**
 * 对象池管理类
 */
let PoolManager = cc.Class({
    start () {
        this.dictPool = {};
    },
    
    /**
     * 根据预设从对象池中获取对应节点
     * @param {cc.prefab} prefab 
     */
    getNode (prefab, parent) {
        let name = prefab.name;
        let node = null;       
        if (this.dictPool.hasOwnProperty(name)) { //指示对象自身属性中是否具有指定的属性(也就是,是否有指定的键)
            //已有对应的对象池
            let pool = this.dictPool[name];
            if (pool.size() > 0) {
                node = pool.get();
            } else {
                node = cc.instantiate(prefab);
            }
        } else {
            //没有对应对象池,创建他!
            let pool = new cc.NodePool();
            this.dictPool[name] = pool;

            node = cc.instantiate(prefab);
        }

        node.parent = parent;
        return node;
    },

    /**
     * 将对应节点放回对象池中
     * @param {cc.Node} node 
     */
    putNode (node) {
        let name = node.name;
        let pool = null;
        if (this.dictPool.hasOwnProperty(name)) {
            //已有对应的对象池
            pool = this.dictPool[name];
        } else {
            //没有对应对象池,创建他!
            pool = new cc.NodePool();
            this.dictPool[name] = pool;
        }

        pool.put(node);
    },

    /**
     * 根据名称,清除对应对象池
     * @param {string} name 
     */
    clearPool (name) {
        if (this.dictPool.hasOwnProperty(name)) {
            let pool = this.dictPool[name];
            pool.clear();
        }
    },

    // update (dt) {},
});

var poolManager = new PoolManager();
poolManager.start();
module.exports = poolManager;

例如:
创建:
let tipsNode = poolManager.getNode(prefab, cc.find(“Canvas”));
回收:
poolManager.putNode(tipsNode);

结语:
欢迎加入微信群一起学习讨论!
请添加图片描述

本文由博客一文多发平台 OpenWrite 发布!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值