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 對象池引用


分享到:


相關文章: