NodePoolEx.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { Prefab, Node, instantiate, isValid } from "cc";
  2. import { UIHelper } from "../common/UIHelper";
  3. import { resLoader } from "../res/ResLoader";
  4. import { NodeEx } from "./NodeEx";
  5. import { NodePool } from "./NodePool";
  6. export class NodePoolEx {
  7. private _pools = new Map<number | string, NodePool>();
  8. private _ready: boolean = false; //节点是否初始化完毕
  9. private _size: number = 10; //池大小
  10. private _res: Prefab = null; //预制
  11. private _clear_time: number = 120; //清理时间(秒)
  12. /**
  13. * 初始化节点池
  14. * @param bundle 包名
  15. * @param url 路径
  16. * @param size 节点池大小
  17. * @param clear 节点池清理时间(秒)
  18. * @param calback 初始化成功回调
  19. */
  20. init(bundle: string, url: string, size: number = 10, clear: number = 120, calback: Function) {
  21. this._pools.clear();
  22. if(this._res){
  23. this._size = size;
  24. this._clear_time = clear;
  25. this._ready = true;
  26. calback && calback();
  27. }
  28. else {
  29. resLoader.load(bundle, url, Prefab, (error: Error, prefab: Prefab) => {
  30. if (error) {
  31. console.error(error);
  32. } else {
  33. this._res = prefab;
  34. this._res.addRef();
  35. this._size = size;
  36. this._clear_time = clear;
  37. this._ready = true;
  38. calback && calback();
  39. }
  40. });
  41. }
  42. }
  43. /**
  44. * 获取节点
  45. * @param id 节点标识
  46. * @param parent 父节点
  47. * @param val 自定义参数
  48. */
  49. getNode(id: number | string, parent: Node = null, ...val: any[]) {
  50. if (this._ready) {
  51. let pool = this._pools.get(id);
  52. if (!pool) {
  53. pool = new NodePool();
  54. pool.init(this._res, this._size, this._clear_time, true);
  55. this._pools.set(id, pool);
  56. }
  57. let template = pool.getNode(parent);
  58. if (template) {
  59. template.node_id = id;
  60. template.reuse(...val);
  61. return template;
  62. }
  63. }
  64. return null;
  65. }
  66. putNode(template: NodeEx) {
  67. if (template && template.isValid) {
  68. let pool = this._pools.get(template.node_id);
  69. if (pool) {
  70. pool.putNode(template);
  71. } else {
  72. template.node.destroy();
  73. }
  74. }
  75. }
  76. clear() {
  77. this._pools.forEach((pool, key) => {
  78. pool.clear();
  79. });
  80. (this._res) && this._res.decRef();
  81. this._res = null;
  82. }
  83. }