Loading and Using JSON Files In Phaser

 

How to load json files into phaser and use them

There are a whole multitude of reasons you may want to load a JSON file into your game. Settings, languages, configurations, level data and so on. This is very simple to do in Phaser!

So lets go ahead and get started. Below you will see an excerpt from a standard phaser state extension class. I’ll link a tutorial here once it’s done!


export default class BootState extends Phaser.State {
preload() {
        this.game.load.json('settings', 'public/config/settings.json');
    }
    create() {
        let mySettings = this.game.cache.getJSON('settings');
        console.log(mySettings.version);
    }
}

The first thing you should notice, other than the fact it’s ES6, is that in the preload function, we call this.game.load.json.

First the key (what you will refer to in order to call back from the cache), the url of the JSON file and optionally an overwrite parameter. If you pass true here, it will overwrite anything in the cache that has the same key.
More documentation on this can be found in the phaser documentation.

Next, inside the create function, I’m grabbing the JSON file out of the game cache. When calling the getJSON function, the game automatically parses the JSON to a usable object for us. I’m storing the settings JSON into the mySettings object.

And finally, I’m consoling out the version property from the mySettings object.

Not lets assume you want to be able to access your settings globalls. Then you can add a settings object to your game object and add your JSON there. You would typically do this in the boot state. For more on state management and structure, read my article here.

Globally Accessible


// boot state
export default class BootState extends Phaser.State {
preload() {
        this.game.load.json('settings', 'public/config/settings.json');
    }
    create() {
        this.game.config.settings = this.game.cache.getJSON('settings');
    }
}

// in any another state that has been started after the boot state
export default class BootState extends Phaser.State {
    create() {
        if(this.game.config.settings.devMode) {
            console.log('in dev mode');
        } else {
        // in a production enviroment
        }
    }
}

It’s also probably worth mentioning that there is no need to globally declare a JSON file such as the config.settings as shown above. I do this usually for readability, or if I know that I will want to change properties in the JSON object. It’s not recommended to change object properties in the cache.

Twitter

Error code 89: Invalid or expired token.

Stay Updated