はじめに
Pixi.jsのLoader(PIXI.Loader)で画像を読み込んだときに、以下の警告がコンソールに出たので中身を見ていきます。
BaseTexture added to the cache with an id [**] that already had an entry
Texture added to the cache with an id [**] that already had an entry
警告がでるコード
PIXI.Loaderでbunny.pngをbunny1, bunny2として読み込み、完了したらPIXI.Containerに追加していきます。
import * as PIXI from 'pixi.js'
const app = new PIXI.Application({
width: 800,
height: 600,
backgroundColor: 0x1099bb,
});
document.body.appendChild(app.view);
const container = new PIXI.Container();
container.position.set(app.screen.width / 2, app.screen.height / 2)
app.stage.addChild(container);
const loader = new PIXI.Loader();
loader
.add('bunny1', 'https://pixijs.io/examples/examples/assets/bunny.png')
.add('bunny2', 'https://pixijs.io/examples/examples/assets/bunny.png')
loader.load((_, resources) => {
const bunny1 = new PIXI.Sprite(resources.bunny1.texture);
const bunny2 = new PIXI.Sprite(resources.bunny2.texture);
container.addChild(bunny1)
container.addChild(bunny2)
})
すると、以下のようにコンソールに警告が出てきます。
読み込む画像パスが被ると警告が出る
結論、読み込む画像のパスが被っているとコンソールに警告が出るようです。Pixi.jsのutilsのPIXI.utils.TextureCache
でキャッシュの中身を見てみると、
textureCacheIdsの配列にキャッシュした画像名と画像パスが含まれています。これは、Texture.ts以下のコード、
/**
* Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object.
*
* @static
* @param {PIXI.Texture} texture - The Texture to add to the cache.
* @param {string} id - The id that the Texture will be stored against.
*/
static addToCache(texture: Texture, id: string): void
{
if (id)
{
if (texture.textureCacheIds.indexOf(id) === -1)
{
texture.textureCacheIds.push(id);
}
if (TextureCache[id])
{
// eslint-disable-next-line no-console
console.warn(`Texture added to the cache with an id [${id}] that already had an entry`);
}
TextureCache[id] = texture;
}
}
のここで追加しています。
if (texture.textureCacheIds.indexOf(id) === -1)
{
texture.textureCacheIds.push(id);
}
警告を出しているコードはその下の
if (TextureCache[id])
{
// eslint-disable-next-line no-console
console.warn(`Texture added to the cache with an id [${id}] that already had an entry`);
}
ここです。TextureCacheの型定義を見てみると、こんな感じ。
/**
* @todo Describe property usage
*
* @static
* @name TextureCache
* @memberof PIXI.utils
* @type {Object}
*/
export declare const TextureCache: {
[key: string]: Texture;
};
おそらく中身はこうなるでしょう。
TextureCache: {
"https://pixijs.io/examples/examples/assets/bunny.png": Texture
}
ですので、TextureCacheオブジェクトの中身に既に同じ画像パスがあれば警告を出していると言えます。同じ画像パスでもPIXI.Loaderで読む込む際に違う名前を付けてあげれば問題はないかなと思います。
キャッシュを明示的にクリアする
キャッシュを明示的にクリアするには、PIXI.utils.TextureCacheを呼び出せば消えるようです。
clearTextureCacheの中身はこんな感じです。
clearTextureCache() {
var key;
for (key in TextureCache) {
delete TextureCache[key];
}
for (key in BaseTextureCache) {
delete BaseTextureCache[key];
}
}