zoukankan      html  css  js  c++  java
  • 【cocos2d-js官方文档】十二、对象缓冲池

    cc.pool的使用场景

    • 经常创建和销毁的元素,例如打飞机游戏里面的子弹等。
    • 不适用的场景:不是很经常创建的物体,比如背景,建筑等。

    如何使用cc.pool

    1. 让你的类支持cc.pool

      首先,你需在需要使用cc.pool来管理的类中实现reuseunuse方法,cc.pool在执行putInPool时将调用该对象的unuse方法,可以在unuse中完成进入回收池前的操作,reuse是当你要从回收池中取出对象时的重新初始化操作,你可以将这个对象初始化为重新可用的状态。

      1.  
        var MySprite = cc.Sprite.extend({
      2.  
        _hp: 0,
      3.  
        _sp: 0,
      4.  
        _mp: 0,
      5.  
        ctor: function (f1, f2, f3) {
      6.  
        this._super(f1, f2, f3);
      7.  
        this.initData(f1, f2, f3);
      8.  
        },
      9.  
        initData: function (f1, f2, f3) {
      10.  
        this._hp = f1;
      11.  
        this._mp = f2;
      12.  
        this._sp = f3;
      13.  
        },
      14.  
        unuse: function () {
      15.  
        this._hp = 0;
      16.  
        this._mp = 0;
      17.  
        this._sp = 0;
      18.  
        this.retain();//if in jsb
      19.  
        this.setVisible(false);
      20.  
        this.removeFromParent(true);
      21.  
        },
      22.  
        reuse: function (f1, f2, f3) {
      23.  
        this.initData(f1, f2, f3);
      24.  
        this.setVisible(true);
      25.  
        }
      26.  
        });
      27.  
        MySprite.create = function (f1, f2, f3) {
      28.  
        return new MySprite(f1, f2, f3)
      29.  
        }
      30.  
        MySprite.reCreate = function (f1, f2, f3) {
      31.  
        var pool = cc.pool;
      32.  
        if (pool.hasObject(MySprite)) return pool.getFromPool(MySprite, f1, f2, f3);
      33.  
        return MySprite.create(f1, f2, f3);
      34.  
        }
    2. 放入回收池

      cc.pool.putInPool(object);
      

      调用此方法将调用对象的unuse的方法,并将对象放入回收池。

    3. 从回收池回收对象

      var object = cc.pool.getFromPool("MySprite", args);
      

      当你需要从回收池中取出一个对象,你可以调用getFromPool传入对象的class,以及传入需要传入的初始化参数,这些参数将被传入reuse方法中,cc.pool将自动调用reuse方法。

    4. 判断回收池中是否有可用对象

      var exist = cc.pool.hasObject("MySprite");
      

      该方法用于查找回收池中是否存在MySprite类的可回收对象。

    5. 删除回收池中的某个对象

      cc.pool.removeObject(object);
      

      将你要删除的对象传入,该对象将会从回收池删除。

    6. 清空回收池

      cc.pool.drainAllPools();
      

      当你需要清除所有回收池中的对象,例如完成游戏要进入其他页面,旧页面中的可回收对象不再有用了,为避免不必要的内存占用,你可以使用drainAllPools删除所有的可回收对象。

    转载请注明:https://blog.csdn.net/qinning199/article/details/41900265
  • 相关阅读:
    2. Add Two Numbers
    1. Two Sum
    22. Generate Parentheses (backTracking)
    21. Merge Two Sorted Lists
    20. Valid Parentheses (Stack)
    19. Remove Nth Node From End of List
    18. 4Sum (通用算法 nSum)
    17. Letter Combinations of a Phone Number (backtracking)
    LeetCode SQL: Combine Two Tables
    LeetCode SQL:Employees Earning More Than Their Managers
  • 原文地址:https://www.cnblogs.com/wodehao0808/p/11929604.html
Copyright © 2011-2022 走看看