Adding an Entity to a script via Javascript

Hi Everyone,

I have a script that takes the camera as an attribute and I want to add it to an entity and populate the attributes using Javascript. I’ve figured out how to add the script (confusingly using entity.script.create) and can add attributes that are simple number or text but I can’t work out how to specify an entity as an attribute? I’ve found some info in the docs but it doesn’t mention this issue (createScript | PlayCanvas API Reference).

The code I’m using (which doesn’t work) is;

var cameraEntity = this.app.root.findByName('Camera');

// create the script
        rotateEntity.script.create('rotate', function(context){
            attributes: {
                cameraEntity: cameraEntity
            }
        });

Anyone got an idea?

Here’s a quick example: https://playcanvas.com/project/1210878/overview/add-script-by-code

Press space to spawn a new box (ideally findByName shouldn’t be used as is O(n) look up, I would have a reference to it in the script and pass it to the create function).

In your case, the second param is supposed to be a JS Object, not a function.

ie

var cameraEntity = this.app.root.findByName('Camera');

// create the script
        rotateEntity.script.create('rotate', {
            attributes: {
                cameraEntity: cameraEntity
            }
        });
1 Like

Thanks so much for that, it’s now working - I’ve obviously got to get a better handle on the syntax in Playcanvas!

I didn’t understand this bit at all though, sorry;

ideally findByName shouldn’t be used as is O(n) look up, I would have a reference to it in the script and pass it to the create function

findByName works by iterating through the hierarchy from graphNode/Entity it is called from until it finds (or not finds) another graphNode/Entity with the name provide.

Instead, I would use an Entity reference via the Script attributes Script Attributes | PlayCanvas Developer Site

Do you mean using;

MyScript.attributes.add('target', { type: 'entity' })

Would ‘target’ simply be the Entity name?

I would recommend to read through all manual pages. There are not that many and it will make your life easier in the long run:

1 Like

You make a good point - I’ve read quite a few but always in the search for something specific. Thanks.

1 Like