How to create/load asset from Json variable (not from file or url)?


#1

Hi,

I store my JSON models in my own database. I load the data in a variable and I tried creating the asset but I don’t figure out how to do that without URL.

In the documentation, every exemple seems to point to functions like “LoadFromURL” or by using the “url” parameter in the asset constructor.

Here’s what I try:

var my_json = JSON.parse(downloaded_json_from_editor);

var asset = new pc.Asset(
    "model_name" //name	String
    "model",     //Type String:	Type of asset
     null,       //file	Object: For assets that don't contain file data use null.
     my_json     //Data Object: JSON object with additional data about the asset
); 

// This will cause an error: Cannot read property 'split' of null
app.assets.add(asset);

//Create a model entity from loaded asset
Var entity = new pc.Entity();
entity.addComponent("model");

//Generate an error: asset.resource is undefined
entity.model.model = asset.resource;
entity.setLocalPosition(0, 0, 0);
pc.app.root.addChild(entity);

I don’t want to put the data from memory in a file or an external url, just to reload it with:
app.assets.loadFromUrl(url, type, callback)

Also, if I try this:

app.assets.add(asset);

or this:

app.assets.load(asset);

I get this error because the 3th parameter in the asset constructor is null

Cannot read property 'split' of null


Dynamic Asset Loading
How to load assets runtime
#2

Another question about this problem: Do we really need to create an asset or can we create and used an entity directly? Like this:

var loader = new pc.ResourceLoader();
var new_model = loader.open("model", my_json);

var entity = new pc.Entity();
entity.addComponent("model");
entity.model = new_model;

entity.setLocalPosition(0, 0, 0);
pc.app.root.addChild(entity);

#3

Here’s how I would do it (excuse the commented out code, I was doing some investigation)

https://playcanvas.com/editor/scene/709011

Code is:

var parser = new pc.JsonModelParser(self.app.graphicsDevice);
var model = parser.parse(data);
var entity = new pc.Entity();
entity.addComponent("model");
entity.model.model = model;
pc.app.root.addChild(entity);

Edit: Note that this is a bit of a hack and working around how the engine was intended to be used.


#4

Thank you for your help! It’s really appreciated.