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


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);;

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 = "";
    var entity = new pc.Entity();

    // Using the vanilla engine version which doesn't return the asset object, "model", function (err, asset) {
        entity.model.model = asset.resource;
        entity.setLocalPosition(0, 0, 0);;

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 (, 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.