Iterate Through All Entities in A Scene

Hi, I thought this would be as simple as:

var entities = this.app.root.getChildren();
or
var entities = this.app.root.children;

but that just returns the root entity. Is there a way to search through everything quickly? Specifically I’m looking to get all all elements in the scene with a render component. Any short way to do this…preferably without having iteration loops on nested children.

Cheers

Perhaps check out the documentation of Entity class?

Specifically:

https://developer.playcanvas.com/en/api/pc.Entity.html#findComponents

So, in your case:

const renderComponents = entity.findComponents("render");

Doesn’t that just find the render component on a single entity? How do I loop through every entity and get every single render component in the scene?

I am doing this…


 var entities = this.app.root.children;//Just returns root
    console.log("entities length is "+entities.length);//jus returns length of 1 (the root- why?)
    // Iterate through all entities and check for the render component
    for (var i = 0; i < entities.length; i++) {
        var entity = entities[i];
        console.log("entities is "+entities[i].name);
        // Check if the entity has a render component
        if (entity.render) {
            //do stuff
        }
    }

Here is a snippet that I use in my UI managers whenever I need to iterate through a bunch of children of an entity. Of course, this will also work on the scene root:

UiManager.prototype.getAllChildren = function(parent) {
    
    let childEntities = [];

    for(let child of parent.children) {

        if(child.children.length > 0) {
            let children = this.getAllChildren(child);
            childEntities = childEntities.concat(children);
        }
        
        if (child.tags.has('opIgnore') || !child.element) {
            continue;
        }

        if(child.name !== 'Untitled' && child.enabled) {
            childEntities.push(child);
        }

    }
    
    return childEntities;

};

You can see the added logic I have in the loop to filter out the things I don’t want, and I’m sure you can easily modify this to return a usable list of entities to act upon.

I hope this is helpful

2 Likes

findComponents() will find all components in both the entity executed on and any of its children. It’s quite a powerful method.