Creating Materials/Textures through script

Hi. I am running a local copy of playcanvas, ie, not using the online editor.
I have a basic model and a texture.
I have uploaded both to the playcanvas online editor and produced JSON files.
I am left with

  • model.json
  • material.json
  • texture.png

I went in to material.json to fix the path to texture.png

So far I can successfully add a model to the game, but am stuck on the process for materials/textures.

// Model
let file = {
   filename: "model.json",
   url: "/model.json"
let model = new pc.Asset("test_model", "model", file); = 123;
model.preload = true;
// This works
let test = new pc.Entity();
test.model.asset = app.assets.find("test_model");

But I am not sure how to add a material.
I have tried this with no luck. I get “Error: Can’t set id and url”

// Material
let file = {
   filename: "material.json",
   url: "/material.json"
let material= new pc.Asset("test_material", "material", file); = 333;
material.preload = true;
// This also fails, but, probably for other reasons
test.model.asset = this.engine.assets.find("test_model"); 
test.model.meshInstances[0].material = material.resource;

So how do I use code to create a material from a downloaded material.json and also apply it to a model or entity?

Hi @tones31,

Can you try loading the asset after adding it to the assets registry?


Your code seems correct, this line should apply the material to the model, if it was correctly loaded:

test.model.meshInstances[0].material = material.resource;

Hm… I’ve tried that, among a few other things. Now I am also noticing that


is null even after setting test.model.asset. Does this indicate something wrong with the entity or with the model asset?

Most likely the model hasn’t been loaded correctly. Can you check in addition the following for being null?


Actually, test.model.model is null! And yet I see the models rendered on the canvas! Just no texture of course.

It looks like assets are not loaded yet…
When I create them, there’s a network request for each .json asset.
But the are still pending while I am then trying to assign them to an entity.
I have preload set to true, and I call load as you suggest for mat/model, but they are not loaded fast enough. Is there a blocking way to preload?

Not sure what’s going on here, maybe try uploading your project to a GitHub repo so we can take a look.

The Playcanvas engine examples are a good place to see how engine only asset loading should work:

Hm, do I need to be using app.assets.loadFromUrl ?

You can use that as well, it takes care of creating the and returning the a new pc.Asset instance. So there is no need creating it manually and adding it to the assets registry.

I went with loadFromUrl and it really solved all of my problems.

1 Like