Instantiate meshes for each child object using traverse

hi everyone,

please take a look on this model in blender,
it has three objects

what i want is to load and position another 3d object on each lightpos object

here what i have tried :

1 - export to obj
2 - traverse the loaded 3d model and store the child objects in an array
3 - load the second object and make a clone as a child for each sub object

here the code :
var scene, mainobj;
var lightpos = [];
var loader = new THREE.OBJLoader();
loader.load(

            "mainobject.obj",
         
            function (obj) {
            
   `mainobj = obj;`
                scene.add(mainobj );
            
               lightpos.splice(0,lightpos.length);
               mainobj .traverse( function ( child ) {
                if ( child instanceof THREE.Object3D  ) {
                 
                
                    if ((child.name).startsWith("lightpos"))
                    {
                        lightpos.push(child);
                    }
                    }});
            });     
		
		......

then with some button click
var loader = new THREE.OBJLoader();
loader.load(

            "childobject.obj",
         
            function (obj) {
 
                  var mesh = new THREE.Mesh(obj.geometry);
                lightpos.forEach(function(element) {
                
                   var instance = mesh.clone();
        
                    element.add(instance);
                 });

but no child object is rendered ,
and if i console log the mainobj variable , i can see that the child objects have been added

any idea on how to achieve this please ?

1 Like

Just an idea: Have you ensured “childobject.obj” is loaded properly?
If so; you can log the child positions to make sure they are where you want.

the child objects are loaded according to the console
and theirs positions are (0,0,0)

also their respective parents are the childs objects referenced during the first mainobject travese .

I would check that the second object is loaded as a normal object to be sure, if you have not done it yet.

yes the second object is loaded and the instance are created on the success callback …

then with some button click
var loader = new THREE.OBJLoader();
loader.load(

    "childobject.obj",
 
    function (obj) {

          var mesh = new THREE.Mesh(obj.geometry);
        lightpos.forEach(function(element) {
        
           var instance = mesh.clone();

            element.add(instance);
         });

the console.log show all the objects created in the tree …

Then I can only suggest to debug objects positions.

all the objects positions are 0,0,0 :confused:

And the lightpos ones?

all of them

Perhaps…

lightpos.forEach( function( element ) {
    var instance = mesh.clone();
    element.computeBoundingBox();
    element.getCenter( instance.position );
} );

after many tries it seem to work with collada files …