Search code examples
javascriptthree.jsaframe

Three js get child object from imported model


I imported a 3D model which has a few child objects and now I would like to get a specific child mesh.

When I use .getObjectByName("Cylinder", true) I always get undefined back, although the model has a child object with the specifed name:

enter image description here

Is there a way to get the child object?


Solution

  • A piece of code would be useful, but there is a pretty common issue happening when You are trying to access the model properties before it actually loads.

    Until the model actually loads, You can't access it's properties.

    I would suggest listening for the model-loaded event, the gltf-model, and the obj-model. It should work like this:

    <script>
    AFRAME.registerComponent("modelhandler", {
      init:function() {
         this.el.addEventListener("model-loaded", (e)=> 
         let child = obj.getObjectByName( "Cylinder", true );
         console.log(child);
       });
    }
    </script>
    
    <a-entity gltf-model="url(/path/to/model.gltf)" modelhandler></a-entity>
    

    If that won't work, You can also try setting a timeout for 5 seconds ( 99% the cube, and a sphere will load within 5 secs), and then trying to grab the child objects. Try putting something like this in the component:

    setTimeout(()=>{
      let child = obj.getObjectByName( "Cylinder", true );
      console.log(child);
    }, 5000});
    

    Otherwise, at least You'll know the issue isn't about the loading.