How to load a model from json and add it to the scene by code

Hi!

I just exported a 3D model from Playcanvas and it give me a json file. Perfect. Now I upload this json file in the assets directory and try to load and add it to the scene like this.

ModelLoader.attributes.add('jsonAsset', { type: 'asset', title: 'My json asset of the 3D model' });

ModelLoader.prototype.initialize = function() {
    
    var cubeModel = new pc.Entity();
       
    cubeModel.addComponent("model", {
        type: "mesh",
        asset: this.jsonAsset
    });

    cubeModel.setLocalPosition(0, 1, 0);
    this.app.root.addChild(cubeModel);
};

It’s not working and a get this error: asset.resource.clone is not a function

My json is very similar to this one: Playcanvas JSON format
My goal is to do something similar to this at the end: Dynamic Asset Loading
Also another question related to this: Use The Canvas Engine To Load The Local Json Model

Thank you for your help

Refer to this post here: Importing 'raw' JSON from other projects

If you are still having problems, can you post a link to your project please?

Thank you for your help. It’s working as expected.

Here’s my working code to help other peoples with the same question:

    var modelURL = "http://myURL.com/model.json";
    var entity = new pc.Entity();

    // Using the vanilla engine version which doesn't return the asset object
    this.app.assets.loadFromUrl(modelURL, "model", function (err, asset) {
        
        entity.addComponent("model");
        entity.model.model = asset.resource;
               
        entity.setLocalPosition(0, 0, 0);
        pc.app.root.addChild(entity);
    });

Actually, its working because the structure around the exported json is exactly the same. I mean, when you export a 3D model, it export multiple JSON files and textures in folders. Beside the JSON that I load, there is a model.mapping.json that is automatically load, which give the path to the others related assets.

My question is now: Can we have the control on the model.mapping.json? What should I do if I want to delete it or move it to another directory? What if I want to load another material and I don’t want the one in this mapping.json?

Thank you for your help. :slight_smile:

You can. If you open up the file you can see it’s just paths to other assets.

IIRC, if you load it the way I’ve done here (https://playcanvas.com/editor/code/501253?tabs=8936727), it has to be in the same directory as the model JSON. Again, it’s needed if you load the way I’ve done in the link, deleting it will cause issues.

However, you can load the model JSON without a mapping. It just can’t be done via loadFromUrl last time I tried it.