Jump to content

Lazy loading, load large graphics only when needed, how?


Recommended Posts

I'm working on a game with several states, a mainmenu state, level select, game state etc. and I use a preloader which loads all the graphics and sounds needed for all these states. There is also a cut-scene state, which contains an intro (and outro) to the game's story. This cutscene state is heavy on graphics, I mean it uses about 1/3rd of MBs of the graphics files and these graphics files are only used in this state.

It is possible to just play the game and skip the intro entirely and most players will not see the outro (game ending) on the first few tries. So most of the time players will not see this cutscene state and I don't want to waste bandwidth on always loading these graphics. Also once the player gets to the cut scene they can play it more than one time, so once the graphics are loaded they don't need to be loaded again. I read that this process is called "Lazy loading"

So my question is; How can I "lazy load" the graphics of just this one state? There is a preloader state that loads assets for all states, but only this one state is an exception. And on a side note; how do I check if graphics are already loaded so I can only load them once?

Link to comment
Share on other sites

You can create a new Phaser.Loader object on your own that isn't tied in with any states. It's the same as game.load, but now you can use it for lazy loading :)


let loader = new Phaser.Loader(this.game);
loader.image(outro, 'assets/images/outro.png');
loader.onLoadComplete.add(() => {
    //Do something here to signal loading has finisged
}, this);

 And on a side note; how do I check if graphics are already loaded so I can only load them once?

The browser already know this, if you load the same assets twice, the browser will return the same result. No idea how Phaser handles duplicates in this regard.

Link to comment
Share on other sites

Thanks for the reply, but since each state has its own preload function, I figured that I can just do something like this in my IntroState:

IntroState.prototype = {
    preload: function() {
        // check if intro graphics are not yet loaded
        if (!this.cache.checkImageKey('face_a')) {
            // load all intro images
            this.load.image('background', 'assets/background.png');
            this.load.image('face_a', 'assets/face_a.png');
            this.load.image('face_b', 'assets/face_b.png');
            // etc.

    create: function() {
        // display sprites
        var back = this.add.sprite(0, 0, 'background');
        var spr = this.add.sprite(100, 100, 'face_a');
        // etc.


Link to comment
Share on other sites


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...