cocoscreator 对象池引用

  1. 为什么要用对象池

在运行时进行节点的创建(cc.instantiate)和销毁(node.destroy)操作是非常耗费性能的,因此我们在比较复杂的场景中,通常只有在场景初始化逻辑(onLoad)中才会进行节点的创建,在切换场景时才会进行节点的销毁。

通过以下步骤来使用对象池

<code> properties: {
\t // 预制体
itemprefab :cc.Prefab,
// 界面显示 节点数 和 对象池中的数
textString:cc.Label,
parentNode:cc.Node,

},/<code>
<code>  onLoad () {
//1. 初示化 对象池
this.itemPool = new cc.NodePool();
},/<code>
<code> // 2 向对象池增加节点
addPool: function () {
let item = null;
// 通过 size 接口判断对象池中是否有空闲的对象
if (this.itemPool.size() > 0) {
item = this.itemPool.get();

// 如果没有空闲对象,也就是对象池中备用对象不够时,我们就用 cc.instantiate 重新创建
} else {
item = cc.instantiate(this.itemprefab);
}

// 将生成的加入节点树 两种方法

// item.parent = this.parentNode;
// 第二种
this.parentNode.addChild(item);
this.textString.string = "node:"+this.parentNode.children.length + "| 对象池:" +this.itemPool.size();
},/<code>
<code>// 3 删除节点 回收节点放入对象池中
subsidePool:function(){
for(let i= this.parentNode.children.length - 1 ; i>= 0 ; i--){
console.log(i);
this.itemPool.put(this.parentNode.children[i]);
break;
}

this.textString.string = "node:"+this.parentNode.children.length + "| 对象池:" +this.itemPool.size();
},/<code>

制作界面:


cocoscreator 对象池引用


效果图:


cocoscreator 对象池引用


分享到:


相關文章: