How to detect when a child is added?

Hi,

I’m in the need of setting the layer property of a Object3D and all it’s children. My issue is that children are added during the lifetime of the parent, and they are added from very different places and circumstances. Therefore I cannot simply traverse the parent to set it all when instanced. The hierarchy of parent/child relations is very deep so it won’t suffice to traverse children at instancing.

Basically what I want to do is know whenever a child has been added somewhere in the hierarchy so that I can then set the properties I need with the help of a callback. Is there any way to know this? If only knowing for a direct child added would be sufficient as well I think.

I guess a naive approach would be to traverse the children during render, but I just have a feeling the performance will take a huge hit.

Any suggestions?

Thanks
BR

So it’s not sufficient if you know when the child object was added to the scene graph? If not, you could add an event listener to the added event like demonstrated in the following fiddle:

https://jsfiddle.net/menq1045/1/

Otherwise you probably need the logic from this PR: https://github.com/mrdoob/three.js/pull/16934

Now that I think of it it would actually be sufficient to know when it’s added to the scene graph as I cab then know both the child and the parent. Is there any built in way to do this without adding an event listener on every possible child?

Thanks

Nope, you need to work with event listeners.

Change the behavior of add function at the source.
Or you can add this to your script. Objec3D_add.txt (747 Bytes)

Nope, you need to work with event listeners.

It’s pretty convoluted to do this at the moment. You have to override add and remove functions in order to properly add and track the events.

Now that I think of it it would actually be sufficient to know when it’s added to the scene graph as I cab then know both the child and the parent. Is there any built in way to do this without adding an event listener on every possible child?

That’s what that PR #16934 helps do. If you’re able to track when a child is added to an object (not when an object is added as a child, which is what three.js supports now) then you can track modifications of a subtree by adding and removing event listeners when childadded or childremoved are fired.

PR #19012 was also made to handle cases like this where you want layers to apply recursively. Feel free to comment on either if you’d find them helpful to be added.