Creating entity and adding script component at runtime

I have an object in a scene with a script to create other entities. As those entities are created I’d like to attach a script to them. The script is “doEntityStuff.js” and it lives in the project.

I’ve been trying a few different ways to do this without any luck.

The first step of finding it doesn’t seem to return anything.

Any ideas? Is there a different approach I should be considering?

var EntityCreator = pc.createScript('EntityCreator');

// initialize code called once per entity
EntityCreator.prototype.initialize = function() {

    
    // find the asset in the registry
var asset = this.app.assets.find("doEntityStuff");
// set up a one-off event listener for the load event
this.app.assets.once("load", function (asset) {
    // asset.resource is now ready
    console.log("script is loaded");
    var entity = new pc.Entity();
    entity.addComponent("script");
    entity.script.create("doEntityStuff");
}, this);
    
};

Hi @noah_mizrahi,

Your doEntityStuff.js script is being loaded and added to the script registry automatically (keep the preload property set to true). So you don’t have to find the script asset and load it.

This part of your code should be enough:

    var entity = new pc.Entity();
    entity.addComponent("script");
    entity.script.create("doEntityStuff");

Also for the script to execute you will need to add your entity to the active scene, as child to another entity or to the Root entity:

    var entity = new pc.Entity();
    entity.addComponent("script");
    entity.script.create("doEntityStuff");

    // final step
    this.app.root.addChild(entity);

Thanks very much. I was seeing that entity.script.doEntityStuff was being defined with your help but I wasn’t seeing the script run.

1 Like

One more issue. Attaching the script at runtime works in isolation. When I try it within the context of loading other scenes I get an error “undefined is not an object (evaluating ‘this.app.root’)”. I imagine I will need to manage this in the scene loading but not sure yet how to.

Could you share your scene changing/loading code?