How to load assets asynchronously with Phaser 3
Written in November 18, 2021 - 🕒 1 min. readOn Phaser 3 you can pre-load your assets in a function called preload
so they are ready to use when the function create
starts. But what if you need to wait for an API request before loading an asset?
Unfortunately, you can’t simply make the preload
function an async
function and force it to wait for your API calls, but there are ways around it.
Using the Rex Await Loader Plugin
rexrainbow is a great developer that brings a lot to the Phaser community, with a documentation website full of Phaser examples and a bunch of great Phaser plugins.
The Rex Await Loader Plugin can be loaded in the global game context by adding it to the plugins
attribute in the Phaser config.
import AwaitLoaderPlugin from 'phaser3-rex-plugins/plugins/awaitloader-plugin.js';
const game = new Phaser.Game({
...config,
plugins: {
global: [
{
key: 'rexAwaitLoader',
plugin: AwaitLoaderPlugin,
start: true,
},
],
},
});
Then in the preload
scene:
preload() {
this.load.image('image', 'path/to/image.png');
this.load.rexAwait((successCallback, failureCallback) => {
fetch('localhost', {
method: 'GET'
}).then(() => {
// do stuff then call the success callback
successCallback();
});
});
this.load.image('image2', 'path/to/image2.png');
}
Using the native Phaser Loader
To avoid loading external plugins, there is also an option to use the native Phaser Loader, as described by yannick.
preload() {
const asyncLoader = (loaderPlugin) => new Promise((resolve, reject) => {
loaderPlugin.on('filecomplete', resolve).on('loaderror', reject);
loaderPlugin.start();
});
const doStuff = async () => {
await asyncLoader(this.load.image('image2', 'path/to/image2.png'));
};
this.load.image('image', 'path/to/image.png');
doStuff();
this.load.image('image3', 'path/to/image3.png');
}
I don’t know how to conclude this post so there you go, I hope this will be useful for someone out there in the internet. If this helped you in any way, don’t forget to leave a comment.
Tags:
Related posts
Post a comment
Comments
Nicolás on 1/13/22
Hi. I follow all your tutorials. And i was wondering if you can make one of how to deal with big tilemaps like open worlds