How to preload dynamically generated assets?

Hi there,

Right now I have a script attached to the Root entity that generates Canvas Fonts and adds them to the Assets Registry.

The styles to be generated for Canvas Fonts, such as fill color and outline color, are set up as attributes of that same script (a JSON attribute). The JSON is attached as an attribute through the Editor.

I added the creation of those Canvas Fonts assets to the initialize function, but the texts using those Canvas Fonts are “popping up” after a while from game startup. Is there a way to stop that from happening, so that the texts are displayed as soon as the loading screen is gone and the game screen is shown? I suspect it is because the initialize doesn’t happen until the Root entity appears in the scene when the game starts…

I am using 2 scripts, one to create the Canvas Font asset and the other to set that asset as a font of the text.

Here are some code snippets of how I tried to approach it:

canvasFontGenerator.js - Added to the Root entity

CanvasFontGenerator.prototype.initialize = function () {

    let canvasFont = this.canvasFont;

    canvasFont.asset = new pc.Asset(canvasFont.name, 'font', {
        url: ''
    });

    this.app.assets.add(canvasFont.asset);
    canvasFont.asset.loaded = false;

    const font = this.renderCanvasFont(canvasFont);
    font.createTextures(canvasFont.charset);
    canvasFont.asset.resource = font;
    canvasFont.asset.loaded = true;
    canvasFont.asset.fire('load', canvasFont.asset);
};

setCanvasFont.js - Added to some entity with Text ElementComponent

SetCanvasFont.prototype.initialize = function () {

    const canvasFontAsset = this.app.assets.find(this.fontName, "font");

    canvasFontAsset.ready(() => {
        this.entity.element.fontAsset = canvasFontAsset;
    }
};

Any help is much appreciated it!

Hi Tsukiyu

Maybe you could edit the loading screen script like

    //app.on('start', hideSplash);
    app.on('mystart', hideSplash);

and then in your font scripts you can fire the ‘mystart’ event after your font is loaded.

I was going to suggest Kulodo1133 mentioned too with the addition that you could have a startup scene that creates all the assets you need before loading the main game/app.

So the logic would roughly be:

preload starts → show loading screen → preload ends → load startup scene → create assets → load main scene → hide loading screen.

1 Like