[SOLVED] My script affects only one object

Hello guys i have 5 same object with the same name and i want my script to affect each of them, however it only affects the first object and not all.

only this one is affected

Hello @smokys ,

I guess when you are using this.app.root.findByName then it target 1st entity only…
You may need to be specific…

Can you share project link so i can take a better look…

If you want to find more than one entity, you should use .find() method:
https://developer.playcanvas.com/en/api/pc.Entity.html#find

.findByName() will always return only one result, the first one it finds. On the other hand, .find(attr [, value]) will return an array of entities, which you then need to iterate over and do your logic on each.

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

so findByName("trap_final[4]) if there is 5 entities ?

var entities = this.app.root.find('name', 'some duplicate name');  
// entities === [entity, entity, entity, ...]

entities.forEach(function(entity) { 
    // do your logic here with each entity that has a duplicate name
    console.log(entity);
});

should not it be var entities = this.app.root.find(['name', 'some duplicate name']); ??

EDIT: nah it probably should not, either way i could not implement for each so i renamed objects and created line for each object in my script

Hello @smokys! The best way is to give the entities the same tag and use findByTag() in your script. Then you can use the way of @LeXXik to do something.

1 Like

Yup i tried findbytag first but it threw error as it could not find a script attached on those objects, when i used findbyname it was all ok

upper line works and second one doesnt work

image

and throws this error

Are you sure all entities with that tag has a script component?

Put them under a parent and then do this in your script:

var entity = this.app.root.findByName('the parent');

entity.children.forEach(function(node){
// do what ever for each of the children...
});
1 Like

Yes im pretty sure, i even tried just one object with that tag which has a script attached… also it says object is undefined, not the script. i tried also rename the tag and try new but still no success

I have to access a script of those children

var entity = this.app.root.findByName('the parent');

entity.children.forEach(function(node){
   node.script.scriptname.whateverthefunctionis();
});
1 Like

Probably you get the same error because I don’t think it’s because of the findByTag() method.

I think the easiest way was just find by tag but that somehow not working

.findByTag() returns an array of entities. So, you need to iterate over an array of objects and access the .script property of each object.

var entities = this.app.root.findByTag('som-tag');
for (var i = 0; i < entities.length; i++) {
    var entity = entities[i];
    var trap = entity.script.trap01Tronball;
}
1 Like

Ah, my bad. Sorry.

but still throws error

image