Dynamic loading : issue when loaded twice

Hi, I’m making a little program where user can click a button, it loads an image and shows it.
Let’s say we have 2 buttons, one loads image1 and the other loads image2, when you load an image, it remove the previous one on the stage.

homeScene.create = function () {  
    scene = homeScene.add.container();
    homeScene.load.on('filecomplete', onFileComplete, this);
    bt1 = homeScene.add.sprite(0, 0, 'bt').setOrigin(0, 0).setInteractive({ useHandCursor: true }).on('pointerdown', () => click('img1','img1_file.png'));
    bt1 = homeScene.add.sprite(0, 50, 'bt').setOrigin(0, 0).setInteractive({ useHandCursor: true }).on('pointerdown', () => click('img2','img1_file.png'))
}

function click(key, file){
    scene.removeAll(true);
    homeScene.load.image(key, file);
    homeScene.load.start();
}

function onFileComplete(key, type, texture) {
    console.log("loaded ", key);
    let img = homeScene.add.sprite(50,0, key).setOrigin(0, 0);
    scene.add(img);
}

It works great, if I click bt1 it shows image 1, then bt2 it removes img1 and show img1 BUT if I click again on bt 1 nothing happens. I think it’s something about cache but I’m quite new to Phaser and did not understand everything yet.

(btw, in my program it will load an image AND an associated mp3 file, so there probably must be a cache issue with it too).

I find some kind of solution but I don’t know if it’s a great idea, feel free to comment this :slight_smile:

function click(key, file){
    scene.removeAll();    

    if(!homeScene.textures.exists(key)){
        homeScene.load.image(key, file, true);
        homeScene.load.start();
    }else{
        let img = homeScene.add.sprite(0, 0, key).setOrigin(0, 0);
        scene.add(img);
    }
}

Do all your loading in a homeScene.preload() method. Then there’s no need for load.start() or on('loadcomplete').

1 Like

In fact there will be 100’s of images and mp3 to load, so it has to be dynamic.
Btw I did not find how to retrieve mp3 from cache, but still searching.

As you like.

Phaser doesn’t load the same key/type twice, so your onFileComplete() was never getting called a second time.

Audio is in cache.audio.

1 Like