NodePool.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. var NodePool = cc.Class({
  2. name: 'NodePool',
  3. properties: {
  4. prefab: cc.Prefab,
  5. size: 0
  6. },
  7. ctor () {
  8. this.idx = 0;
  9. this.initList = [];
  10. this.list = [];
  11. },
  12. init () {
  13. for ( let i = 0; i < this.size; ++i ) {
  14. let obj = cc.instantiate(this.prefab);
  15. this.initList[i] = obj;
  16. this.list[i] = obj;
  17. }
  18. this.idx = this.size - 1;
  19. },
  20. reset () {
  21. for ( let i = 0; i < this.size; ++i ) {
  22. let obj = this.initList[i];
  23. this.list[i] = obj;
  24. if (obj.active) {
  25. obj.active = false;
  26. }
  27. if (obj.parent) {
  28. obj.removeFromParent();
  29. }
  30. }
  31. this.idx = this.size - 1;
  32. },
  33. request () {
  34. if ( this.idx < 0 ) {
  35. console.log('=========== NodePool: 对象池已满 ===========')
  36. return null;
  37. }
  38. let obj = this.list[this.idx];
  39. if ( obj ) {
  40. obj.active = true;
  41. }
  42. --this.idx;
  43. return obj;
  44. },
  45. return ( obj ) {
  46. ++this.idx;
  47. obj.active = false;
  48. if (obj.parent) {
  49. obj.removeFromParent();
  50. }
  51. this.list[this.idx] = obj;
  52. }
  53. });
  54. module.exports = NodePool;