给大家提供一个小小的工具类;有不好的地方可以指出,谢谢!
这个工具类主要是针对节点池加载,出现代码冗余的一个封装,没有其他特殊效果。
话不多说,我们先来看一下正常节点池的加载与移除:
@property(cc.Prefab)
pfbTest: cc.Prefab = null;
@property(cc.Node)
content: cc.Node = null;
private _nodePool: cc.NodePool;
public get nodePool() : cc.NodePool {
if (!this._nodePool) {
this._nodePool = new cc.NodePool();
}
return this._nodePool;
}
updateNodes() {
const array = Array.kq_array(10, 1);
this.putNodes();
array.forEach((value) => {
const node = this.nodePool.get() || cc.instantiate(this.pfbTest);
this.content.addChild(node);
const comp = node.getComponent(TestChildComp);
comp.updateValue(value);
})
}
putNodes() {
this.node.children.slice().forEach(node => this.nodePool.put(node));
}
当工程中少部分地方用到节点池加载的话还比较好。但是,如果使用节点池的地方多了,那就会有大量的代码冗余,重复写一些写过的代码。
那么接下来 NodePoolTool 类就诞生了,我们来简要的看一下示例:
@property(cc.Prefab)
pfbCell: cc.Prefab = null;
@property(cc.Node)
content: cc.Node = null;
private _npCell: NodePoolTool<RankCellComp>
get npCell() {
if (!this._npCell) {
this._npCell = new NodePoolTool(this.pfbCell, this.content, RankCellComp)
}
return this._npCell;
}
updateNodes() {
const array = Array.kq_array(10, 1);
this.npCell.loadNodes(array, (comp, data) => {
comp.updateValue(data);
})
}
putNodes() {
this.npCell.clear();
}
我们发现这里使用封装之后,主体部分只需要几行很简单的代码就可以搞定!!!
代码在这NodePoolTool.zip (1.2 KB)