Setting up font by script?

Hello all!

I’m having a hard time dynamicaly setting up fonts. So. I have a json and a png that was generated from playcanvas editor and added to a server. The idea is to have a way to override fonts in a game.

I create my font like this where texture is an array with one element (png) and json is the meta data generated by playcanvas :
var font = new pc.Font(texture, json);
var asset = new pc.Asset(name, “font”, {
url: “”
});

asset.tags.add(tag);
asset.resource = font;
asset.loaded = true;
app.assets.add(asset);

then I try to replace a font on entity like this :

var app = this.app;
var self = this;

var entities = app.root.findByTag(tag);
var entitiesLoaded = 0;
var entitiesTotal = entities.length;

.
.
.

// Start loading all the assets
for(var i = 0; i < entities.length; i++) {

    var entity = entities[i];
    if (entity.element && entity.element.text) {
        console.log('font is: ' + entity.element.Font); //undefined
        entity.element.Font = asset.resource;//font previously created
        console.log('after font is: ' + entity.element.Font);
    } 
}      

Thanks for your support

Mykel

Here is an engine only example of loading a font asset from JSON

https://playcanvas.github.io/#user-interface/text-basic.html

Thanks! It works! But I think I found a bug in the engine in case the json your looking for at url is not there: is it possible that :

var data = upgradeDataSchema(response);

should be after we confirm that we have data (in the !err case)?

var self = this;
			if (path.getExtension(url.original) === '.json') {
				http.get(url.load, {
					retry: this.retryRequests
				}, function (err, response) {
					var data = upgradeDataSchema(response);
					if (!err) {
						self._loadTextures(url.load.replace('.json', '.png'), data, function (err, textures) {
							if (err) return callback(err);
							callback(null, {
								data: data,
								textures: textures
							});
						});
					} else {
						callback("Error loading font resource: " + url.original + " [" + err + "]");
					}
				});

Do you have a repro case for when this goes wrong out of interest? It does feel like you are right.

I think the most simple way to go is to rename arial.json in the exemple you sent me and see if you get the same error?

I use loadFromUrl.

app.assets.loadFromUrl(someurltofontjson, “font”, function (err, asset) {

    if(err) {
        
    } 
    else {

    } 
});

Basically what im working on right now is a simple game which can be customized by hot loading assets from urls. If nothing is found at location, just load the default game asset.

Good shout, submitted a PR: https://github.com/playcanvas/engine/pull/2450

In the short term, you may have to monkey patch that function for your use case.