function traverseGroups(group) {
let allObjects = [];
group.traverse(function(object) {
console.log(allObjects);
console.log(object);
if(object.type === 'Group') {
allObjects.push(...traverseGroups(object));
} else {
allObjects.push(object);
};
});
return(allObjects);
};
I tried to create an array, then traverse through the group, appending the traverseGroup of the childObject to the array if the childObject is a group, otherwise simply the appending the childObject to the array.
This doesn’t seem to be working, as with the console.log statements I can see that the array seems to remain empty and the object seems to be the same every time (Object { isObject3D: true, uuid: "bd88a831-bd88-4d88-acfc-dff9118f960f", name: "Scene", type: "Group", parent: {…}, children: (13) […], up: {…}, position: {…}, rotation: {…}, quaternion: {…}, … }
).
I already asked Bing about this, and I followed a couple of it’s suggestions, such as using === rather than ==, and .push() rather than .concat()
Can you please help?
Your observation that the same object is printed in the console is correct.
Here is a small hint:
According to the documentation of Object3D.traverse
, it executes the callback on the provided object and all descendants. So, if you call traverseGroups
with a group, the first value of parameter object
will be the same group … and this will push the execution into infinite loop … until the stack gives up.
I hope you can see how to fix your code (i.e. I do not want to steal from you the joy of fixing your own code). However, let me know if you need more help.
Is there a function that only does it on the descendents, not the current object?
Here is one solution using your style. Does it do what you want?
function traverseGroups(group) {
let allObjects = [];
group.traverse( function(object) {
if( object.type !== 'Group' )
allObjects.push(object);
} );
return allObjects;
}
2 Likes
You can loop through all immediate descendents of object
with a loop:
for (let child of object.children) {
// do whatever you want with child
}
2 Likes
No, because I want it to go inside groups and return all the individual elements inside them.
I don’t get why you’re not just using…
function traverseGroups(group) {
let allObjects = [];
group.traverse(function(object) {
allObjects.push(object);
});
return(allObjects);
};
Won’t this just push all descendants, group or not, to the allObjects array?
Yeah I tried that it’s working now, thanks!