// NodePoolMgr.ts const { ccclass } = cc._decorator; @ccclass export default class NodePoolMgr extends cc.Component { // 私有属性 private nodePool: cc.NodePool = null; private itemPrefab: cc.Prefab = null; onLoad() { this.init(); } /** * 初始化组件 */ private init() { this.nodePool = new cc.NodePool(); } /** * 获取一个列表项节点 * @param prefab 列表项预制体(可选,如果不传则使用之前设置的预制体) */ public getItem(prefab?: cc.Prefab): cc.Node { // 如果传入了新的预制体,则更新当前预制体 if (prefab) { this.itemPrefab = prefab; } let itemNode: cc.Node = null; if (this.nodePool.size() > 0) { itemNode = this.nodePool.get(); } else if (this.itemPrefab) { itemNode = cc.instantiate(this.itemPrefab); } else { console.warn("NodePoolMgr: No prefab available to instantiate item"); } return itemNode; } /** * 回收列表项节点 * @param itemNode 列表项节点 */ public putItem(itemNode: cc.Node) { if (itemNode) { this.nodePool.put(itemNode); } } /** * 设置预制体 * @param prefab 新的预制体 */ public setItemPrefab(prefab: cc.Prefab) { this.itemPrefab = prefab; } /** * 获取当前预制体 */ public getItemPrefab(): cc.Prefab { return this.itemPrefab; } /** * 清空节点池 */ public clear() { // 销毁节点池中的所有节点 this.nodePool.clear(); } /** * 销毁时清理资源 */ onDestroy() { this.clear(); } }