Find child of type/with component

I have a scene with many cameras (each has its own time where it’s enabled).
one of the cameras is a child to an object, and that object has a script called ‘EnterThis’

what i try to do is to perform a ‘Find’ search like FindChildOfType(camera) to get that child and not iterate between all the cams in the scene.
one option is to define the attribute as public and assign it from the inspector.
but is there a way to do this kind of search with code?

There are a couple of ways of doing this but I think the easiest would be to use the entity tags so you can use https://developer.playcanvas.com/en/api/pc.Entity.html#findByTag

thanks alot, ill test it out

however, will it also findByTag a disabled object?

you can get all children that have a camera from the root element with code let allElements = this.entity.findComponents(“camera”);

1 Like

Is there a way to do this on an array of entities instead of from the root node?

No, you will have to iterate over each entity in the array

you could select the entities you want and then do a push

1 Like

Ended up doing something like that. Thanks for the input

1 Like

Hi all, bit late to the party here, but I’ve just put together this helper function if wanting to get elements of a certain type from all children of a given parent.

// Returns an array of pc ElementComponents found on child entities of 
// <parent>  which are of element type <ofType> being one of:
// [pc.ELEMENTTYPE_GROUP|pc.ELEMENTTYPE_IMAGE|pc.ELEMENTTYPE_TEXT]
function getChildElementsOfType(parent, ofType = pc.ELEMENTTYPE_TEXT) {
    var found = parent.children
        .filter((c) => c.element && c.element._type == ofType)
        .map((c) => c.element);
    return found;
}

Hope this might help some people,
Cheers :slight_smile:

2 Likes

Does https://developer.playcanvas.com/api/pc.Entity.html#findComponents not do something similar? (I only found out this function myself not too long ago!)

This doesn’t include deeply nested elements right? If I have a text that is 2 levels deep this won’t work.

Oh ok… here’s a ‘hybrid’ of the above two answers which returns all descendants and also distinguishes between different element types (unlike findComponents which only goes down to element level)…


// Returns an array of pc.ElementComponents found on all descendant
// entities of  <parent> entity  which are of element type <ofType> being one of:
// [pc.ELEMENTTYPE_GROUP|pc.ELEMENTTYPE_IMAGE|pc.ELEMENTTYPE_TEXT]
function getDescendantElementsOfType(parent, ofType = pc.ELEMENTTYPE_TEXT) {
    var found = parent.findComponents("element")
        .filter((e) => e._type == ofType);
    return found;
}
2 Likes