Anthony
Anthony

Reputation: 5433

phaser.io pre-loading data and then pre-loading images

I'm having some trouble with the code below:

CardList.preload = function() 
{
    game.load.text('card_list', '/data/card_list.json');

    var card_list = JSON.parse(game.cache.getText("card_list"));

    // :ISSUE: This code never fires because card_list isn't populated until preload is complete...
    for(var i in card_list)
    {
        game.load.image('hero_card_' + i, 'images/hero_card_' + i + '.jpg');
        game.load.image('hero_tile_' + i, 'images/hero_tile_' + i + '.jpg');
    }

}

Basically, I'm trying to load a list of the cards the player owns (from a JSON file), and then pre-load the images. The problem is, game.load.text() doesn't fire immediately and there's no support for a callback.

Is there a different approach to solve this problem?

Upvotes: 1

Views: 2109

Answers (1)

PhotonStorm
PhotonStorm

Reputation: 3385

Phaser preload functions work by executing all 'game.load' calls in them and building the loader queue from that. Then it starts the loader running - this is how it knows how many files there are to load, how many are left, etc. It also means you can't access a file about to be loaded within the preload function itself.

You've two choices: You could load the card_list.json in a different State (i.e. a Boot State) and then you can parse it and load the assets it lists in a Preloader state. If you look in the Phaser repository in the Project Templates folder you'll find an example set-up that does this.

Option 2 is that your preload function loads just the card_list (and any other assets that you know are safe to load here) and then once loaded you can start another Loader running which loads the actual assets. There is an example of that here: http://examples.phaser.io/_site/view_full.html?d=loader&f=load+events.js&t=load%20events

Upvotes: 2

Related Questions