对象池中对象个数问题

cocos creator 2.4.6
const { ccclass, property } = cc._decorator;

@ccclass

export default class Helloworld extends cc.Component {

@property(cc.Node)

lvNode: cc.Node = null;

@property(cc.Prefab)

lvPrefab: cc.Prefab = null;

private lvNodePool: cc.NodePool = null;

start() {

}

onLoad() {

    this.lvNodePool = new cc.NodePool();

    for (let i = 0; i < 100; i++) {

        let pb = cc.instantiate(this.lvPrefab);

        if (pb) {

            this.lvNodePool.put(pb);

        }

    }

}

createLvItem() {

    let lvItem = null;

    if (this.lvNodePool.size() > 0) {

        lvItem = this.lvNodePool.get();

    } else {

        lvItem = cc.instantiate(this.lvPrefab);

    }

    return lvItem;

}

initData() {

    for (let i = 0; i < 100; i++) {

        let item = this.createLvItem();

        item.parent = this.lvNode;

    }

}

remove() {

    if (this.lvNode.childrenCount > 0) {

        let index = 0;

        this.lvNode.children.forEach(ele => {

            if (ele) {

                index++;

                console.log("回收>>>>>>", index++);

                this.recycleItem(ele);

            }

        })

        console.log("this.lvNodePool>>>", this.lvNodePool.size());

        // this.lvNode.removeAllChildren();

    }

}

recycleItem(item: cc.Node) {

    this.lvNodePool.put(item);

}

onCLickHandle(sender: cc.Event) {

    let target = sender.target.name;

    if (target === "btn1") {

        console.log("初始化");

        this.initData();

    } else if (target === "btn2") {

        console.log("回收");

        this.remove();

    } else if (target === "btn3") {

        console.log("重新创建");

        this.initData();

    }

}

}
有没有大佬 帮忙看一下 对象池回收之后数量怎么变成了原来的一半

1赞

有大佬知道那个地方出问题啦 指明一下

看来了一眼 remove ,这样子写会有问题,建议反过来处理


    remove() {
        if (this.lvNode.childrenCount > 0) {
            let index = 0;

            this.lvNode.children.forEach((ele) => {
                if (ele) {
                    index++;

                    console.log("回收>>>>>>", index++);

                    this.recycleItem(ele);
                }
            });

            console.log("this.lvNodePool>>>", this.lvNodePool.size());

            // this.lvNode.removeAllChildren();
        }
    }
const length = this.lvNode.children.length;
for (let i = length - 1; i >= 0; --i) {
   this.recycleItem(this.lvNode.children[i]);
}

感谢大佬 :grinning:

话说第一种为啥就不行呢 大佬

下标发生了变化

非常感谢 :+1:

该主题在最后一个回复创建后14天后自动关闭。不再允许新的回复。