前幾篇提了 Texture、BaseTexture、PixiJS 的 Cache,
這篇討論 可視物件 的 destroy() 方法
在 PixiJS 的 Container 與 子類別 裡,單純透過父物件 removeChild(),
並不會移除物件本身,只是移出場景。
要完全移除可視物件時,可使用 destroy() 方法
以 SPRITE - Basic 的例子舉例:
執行了 bunny.destroy(); 後:


bunny.destroy();
console.log(PIXI.utils.BaseTextureCache);
在各個 API 的說明裡,都有說在執行 destroy() 後,不要再使用該個物件
執行了 bunny.destroy({texture: true, baseTexture: true}); 後:


bunny.destroy({
    texture:true, // 將 texture 移除
    baseTexture:true // 將 baseTexture 移除
});
若 children 設定為 true 時,會將 destroy() 的其他屬性如 texture: true 與 baseTexture: true 再傳入子物件、孫物件
destroy(options) {
    super.destroy();
    this.sortDirty = false;
    const destroyChildren = typeof options === 'boolean' ? options : options && options.children;
    const oldChildren = this.removeChildren(0, this.children.length);
    if (destroyChildren) {
        for (let i = 0; i < oldChildren.length; ++i) {
            oldChildren[i].destroy(options);
        }
    }
}
會到最底層 DisplayObject 的 destroy() 實作:
destroy(_options) {
    if (this.parent) {
        this.parent.removeChild(this);
    }
    this.removeAllListeners();
    this.transform = null;
    this.parent = null;
    this._bounds = null;
    this._mask = null;
    this.filters = null;
    this.filterArea = null;
    this.hitArea = null;
    this.interactive = false;
    this.interactiveChildren = false;
    this._destroyed = true;
}
相關討論:difference-between-texture-and-basetexture
ivan.popelyshev:
Destroying PIXI.Texture does not free memory, it just makes texture not valid and removes it from image cache, so other sprites wont be able to use it. I really dont know cases when you have to call it :)Destroying PIXI.BaseTexture frees WebGL objects that are bound to it. Call it for dynamic texture that you use or some statics that arent needed anymore.
大意:摧毀 PIXI.texture 並不會釋放記憶體,釋放記憶體時需摧毀 PIXI.BaseTexture,並且確定相對應的 PIXI.texture 不會再被使用
前半小節:
好像都不是很難理解的參數,又好像理解了可視物件的層級關係
可喜可賀 (?)

const bunnyL = PIXI.Sprite.from('assets/basics/bunny.png');
app.stage.addChild(bunnyL);
const bunnyR = PIXI.Sprite.from('assets/basics/bunny.png');
app.stage.addChild(bunnyR);
於先前文章 可知,使用 Sprite.from() 帶入相同網址,會得到同一個 texture
此時若將其一的 texture 刪除
兩個 Sprite 皆會刪除
但只有執行了 destroy({texture: true}) 的 bunnyL 本身與 Texture 被摧毀
bunnyR 沒有執行 destroy(),但是共用的 texture 已被移除,所以 bunnyR 從畫面上消失了

右邊的兔子除了 texture 不見外,其他狀態皆相同
1
false

讀入一隻兔子後,texture 與 baseTexture 狀態:

不帶參數時:texture / baseTexture 皆保留


保留,這是最特別的一個

由於 Sprite 的 Texture、BaseTexture 有可能給不同的 Sprite 使用,destroy 的情形較為複雜


結果:
用不到的 Text,就直接 destroy() 吧




不同類別的可視物件繼承皆繼承自 PIXI.Container,但會覆寫其 destroy() 的方法
從原始檔看各個可視類別的實作:
後半心得:
每種類別的 destroy()方法 實作不同,需視情況執行 destroy()