PondMgr.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import GameLog from "./GameLogMgr";
  2. import LoadMgr from "./LoadMgr";
  3. export default class PondMgr {
  4. private static caches: { [key: string]: any } = {};
  5. private static gamePool: { [key: string]: cc.NodePool } = {}; //对象池?
  6. /**
  7. * 新增对象池
  8. * @param url 名称
  9. * @param prefab 预制体
  10. * @param cnt 个数
  11. */
  12. public static addToCaches(url: string, prefab: any, cnt: number = 1) {
  13. if (url && prefab) { //判断url 和预制体 是否为空
  14. if (this.caches[url]) {
  15. return false
  16. }
  17. this.caches[url] = prefab;
  18. this.createToPool(url, cnt);
  19. return true;
  20. }
  21. }
  22. private static createToPool(url: string, cnt: number = 1) {
  23. //判断 url是否为空,或者 内存中已经存在
  24. if (!url || !this.caches[url]) {
  25. return;
  26. }
  27. //如果 gamePool 中没有存在 的话 , 那么就创建一个 cc.Node
  28. if (this.gamePool[url] == null) {
  29. this.gamePool[url] = new cc.NodePool();
  30. }
  31. cnt -= this.gamePool[url].size();
  32. for (let i = 0; i < cnt; i++) {
  33. let item = cc.instantiate(this.caches[url]);
  34. this.gamePool[url].put(item);
  35. }
  36. }
  37. /**
  38. * 放回对象池
  39. */
  40. public static putNodeToPool(url: string, item: cc.Node) {
  41. if (item == null || url == "" || url == null) {
  42. GameLog.warn('putNodeToPool fail', url, item);
  43. return;
  44. }
  45. //该对象池不存在,重新创建
  46. if (this.gamePool[url] == null) {
  47. this.gamePool[url] = new cc.NodePool();
  48. }
  49. //清空父节点
  50. item.parent = null;
  51. this.gamePool[url].put(item);
  52. }
  53. /**
  54. * 从对象池中获取一个节点
  55. */
  56. public static getNodeFromPool(url: string): cc.Node {
  57. let item = null;
  58. //如果对象池为空,则需要重新创建一下
  59. if (this.gamePool[url] == null) {
  60. this.gamePool[url] = new cc.NodePool();
  61. }
  62. if (this.gamePool[url].size() > 0) {
  63. item = this.gamePool[url].get(); // 对象池 中如果已经存在这个节点了,直接去除就行
  64. } else if (this.caches[url]) {
  65. //没有存在这个节点的话 ,需要根据 caches 创建
  66. item = cc.instantiate(this.caches[url]);
  67. }
  68. return item;
  69. }
  70. /**
  71. * 异步获取节点
  72. * @param url 节点路径
  73. * @param callFun 获取到之后的回调函数
  74. */
  75. public static getAsyncNodeToPool(url: string, callFun: any) {
  76. if (!url) {
  77. GameLog.warn("getAsyncNodeToPool", "url为空");
  78. return;
  79. }
  80. let item = this.getNodeFromPool(url); // 先获取节点
  81. if (item) { //节点存在,调用回调
  82. if (callFun) {
  83. callFun(item);
  84. }
  85. } else {
  86. //节点不存在,只能去加载咯 ,芜湖
  87. LoadMgr.loadPrefab(url).then((prefab: cc.Prefab) => {
  88. this.addToCaches(url, prefab);
  89. item = this.getNodeFromPool(url);
  90. if (callFun) {
  91. callFun(item);
  92. }
  93. })
  94. }
  95. }
  96. }