Search code examples
three.js

Get he mesh from the DracoLoader of ThreeJS


I work on the Draco loader of ThreeJS but I encounter a problem with the loader. I actually need the mesh of the dracofile load but the mesh is not available after i load it with this code:

let mesh;
const loader = new DRACOLoader();
loader.setDecoderPath('./Three/examples/js/libs/draco/')
loader.load('PATHTO drc file', function(geometry) {
    var material = new THREE.PointsMaterial({ size: 0.05 });
    material.vertexColors = false
    mesh = new THREE.Points(geometry, material);
    mesh.position.set(0, 0, -1);
});
console.log(mesh) // print undefined

I need the mesh to perform some operations do you have some clues for this problem?


Solution

  • The loading callback runs asynchronously, so the line immediately afterward runs first and the mesh is defined only later. There are many ways to manage asynchronous programming (I'd suggest https://eloquentjavascript.net/11_async.html as an introduction) but a simple solution in this case would be to put the later code into a callback:

    let mesh;
    
    ...
    
    loader.load('...', (geometry) => {
      mesh = ...
      start();
    });
    
    ...
    
    function start() {
      console.log(mesh);
    }