| 摘要 节点的创建(cc.instantiate)和销毁(node.destroy)操作是非常耗费性能的。如果制作有大量敌人或子弹需要反复生成和被消灭的动作类游戏时,需要使用对象池。 环境 cocos creator 2.4.3 编辑工具HBuild X 像这样的的项目: 子弹,障碍物,敌人都可以使用对象池  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 发布! |