(SOLVED) Entity creation using code

Hi all,

Apologies if this is a bit of a noob question, but I’ve looked through the API guide/user manual/tutorials but I’m not getting anywhere.

I’m essentially trying to create an entity through code rather than using the editor but am falling at the first hurdle as I’m not even able to get a box to appear.

I have applied the following code to the ‘Root’ of the project, my console log shows up so the code is definitely running, but no box is there.

var CreateEntity = pc.createScript('createEntity');

// initialize code called once per entity
CreateEntity.prototype.initialize = function() {
    
    console.log("run");
    
    var box = new pc.Entity();
    
    box.addComponent("model", {
            type: 'box',
        });
    
    box.addComponent("rigidbody", {
            type: 'rigidbody',
        });

    box.addComponent("collision", {
            type: 'box',
        });

};

// update code called every frame
CreateEntity.prototype.update = function(dt) {
    
};

Link to project is - https://playcanvas.com/editor/scene/524322

Any help would be greatly appreciated.

Matt

Just forked it. Most of the code you had there at the time worked for me?

    var box = new pc.Entity();
    
    this.app.root.addChild(box);   
    
    box.addComponent("model", {
            type: 'box',
        });
    
    box.addComponent("script", {
            type: 'script',
    });

Thanks for the reply.

I found my mistake - I had missed out the

           this.app.root.addChild(box);

Still not 100% sure what that does but at least I’ve got the first step! thanks for looking

It adds it as a child to another entity (in this case the root). If the entity is created and not connected to the root in some way (via it’s parent, or it’s parent parent etc), then it will not render.

1 Like

Ah I see, yeah that makes sense. Thank you for the clarification, I really appreciate it.