Properly cleaning up resources when required

I have two scenes in the game and that loads few images on preload(). I need to know the correct way to clear loaded images & other resources when;

  1. Browser tab is reloaded/closed
  2. When loading images in a scene, if the key exists avoid loading that resource.

As of now, when my scene is reloaded(browser refresh) it gives the following error in console:

Texture key already in use: main-lk

So what I tried was:

window.onbeforeunload = function () {
    console.log("unloading window... try to unload cached images");
    game.cache = new this.Phaser.Cache.CacheManager(game);
    game.textures.destroy()
    game.destroy(false);
}

assuming that this will clear everything on a browser refresh. This doesn’t seem to work cause I still get the same error.

Then I tried below code in preload()

this.textures.remove(“main-aq”); ← force removing the image

this.load.image(“main-aq”,[my url]); ← reload the image

When I do that, console shows;

No texture found matching key: main-aq <--this is for removing line
Texture key already in use: main-aq <-- loading line. means this was not cleared with remove

How can I properly release resources onrefresh/reloading scenes ?

There’s nothing you need to do between page reloads. If you’re getting this after reloading, then you’re trying to add two resources by the same key. Either

  • use different assets keys; or
  • remove the texture before loading by the same key, but don’t start the scenes simultaneously.