Insert model from asset library using script

Hello experts.

I’m quite new to Playcanvas and have bumped into a basic problem.
I have imported a .FBX and assigned a script to it, named “Landscaperelated.js”.
I have imported another .FBX, named “tree” and would like to make a routine that pick the tree from the asset library and put several instances of it as children of the landscape. It all seem to work, except the part where a tree is actually placed in the scene (see comments).

Inside Landscaperelated, I have this code inside the initializer:

Landscaperelated.prototype.initialize = function() {
    var app =;
    var mainModel = this;       
    var asset ="tree");
    asset.ready(function (asset) {
        console.log("Asset loaded");
        // Later, put a loop here to generate several trees.
        var objekt = new pc.Model(asset.resource);
        mainModel.entity.addChild(objekt); // Does not work - returns "graphnode is already parented"
        mainModel.entity.model.model = asset.resource; // Does work, but replaces the landscape

I have spent hours on such a small problem. Can someone help me out, please?

Have you seen this tutorial:

Sounds like it’s doing what you want, but with houses instead of trees.

Brilliant - I got so focused on retrieving the assets directly from the asset library that I overlooked other solutions.
Thanks a lot!

Hi, doctorweile.
You can use
to replace
to solve the problem “graphnode is already parented”.

1 Like

Hello WingUNO

I tried that approach before my post while still having hair to tear out, based on another post - but it returned a “objekt.reparent is not a function” error.
My understanding of this command is that it will only work on two entities and that if an asset isn’t present on the stage, it can’t be reparented… or have I misunderstood something?

ah, You are right.

I saw you using
then I regarded objekt as an entity. :sweat_smile:

if you want to add a model to an entity, addComponent might be a good idea.

Thank you for your reply.

I previously gave addComponent a try… but it kept returning (and is still returning an error)

Landscaperelated.prototype.initialize = function() {
    var mainModel = this;
    var entity = new pc.Entity();
    // var objekt = new pc.Model(asset.resource); // Save for when I succeed in adding an empty entity
    // var entity = new pc.Entity(objekt); // Save this as well
    mainModel.entity.addComponent(entity); // Returns ERROR:   System: '[object Object]' doesn't exist

That’s not how you use addComponent. Here is a tutorial on programmatically creating entities .

Ideally you should first read the docs and then try to build something otherwise you will be blocked by simple stuff pretty often…

If you want to add a model component you’d do

entity.addComponent('model', {
    type: 'asset',
    asset: modelAsset

Here modelAsset can either be an asset from a script attribute or a model asset that you find via (see asset registry)