I haven’t been able to find a function that iterates through all entities in a scene. I’m trying to accomplish this in obj.js:
var Obj = pc.createScript('obj');
// initialize code called once per entity
Obj.prototype.initialize = function() {
//iterate through all entities
for (var i = 0; i < EntityTable.length; i++) {
var thisobj = EntityTable[i];
//Do stuff to the entity
}
};
Starting at the root entity (pc.app.root), you can traverse the graph by recursively looping through each of the children.
Untested code:
Obj.prototype.doStuffToEntity = function (entity) {
var i = 0;
for (i = 0; i < entity.children.length; ++i) {
this.doStuffToEntity(entity.children[i]);
}
// Do stuff to entity
};
Obj.prototype.initialize = function() {
this.doStuffToEntity(pc.app.root);
};
Generally, I avoid accessing the app through the global pc namespace instance (which I believe is undocumented). You should really do this.app instead.
Thanks for the responses; I have applied the concept to this code in addition to making my own Entity table so I can access them later. Except it freezes if I try to iterate through the children and the children’s children:
var Game = pc.createScript('game');
Entities = []; //Table containing entities
function initEntity(entity) {
if (entity === undefined)
return;
Entities.push(entity);
for (i = 0; i < entity.children.length; ++i) {
initEntity(entity.children[i]);
}
}
Game.prototype.initialize = function() {
if (!this.entity.tags.has("root"))
return;
initEntity(this.entity);
};
This is probably because you have not declared i as a var in the scope of function initEntity. This means that i will be declared in global scope on the window object and when you reenter the function recursively, i will be the wrong value. If you put var before the i in the for loop, you should be good.