Call Variable Outside of Defined Scope

Hi, is there a way to call var “mesh” outside of the load function? Code is below.

var loader = new THREE.GLTFLoader();
loader.load( 'cube.glb', function ( geometry ) {

geometry.scene.traverse( function ( node ) {

        if ( node.isMesh ){
            mesh = node;
            //some irrelevant scaling and material stuff is done here

  //call mesh here

What do you mean with “calling”? What you can do is creating a empty THREE.Object3D before loading the mesh and add the mesh to it once it’s loaded, using the object as proxy container.

But it depends on what you mean with “call mesh here”, the mesh itself won’t be available at this point since it’s loaded asynchronously.

1 Like

Do you mean something like this?

 var cube = new THREE.Object3D();

   mesh = cube;


No that won’t work, what do you want to do at the “call mesh here” line?

1 Like

My approach is probably wrong then. I have 3 shapes that i’m trying to display in scene. Each shape has an html button that when pressed, will add the respective shape to the scene. To do this, I wouldn’t need to “call mesh” outside of the loading function. However, I was going to implement code where if the user pressed another shape’s button, the shape currently displayed would be replaced by the new shape. Hence why I need to “call mesh” outside.

EDIT: Basically I could call scene.remove(cube); and scene.add(circle); anywhere

Yes you can call on the loading callback too of course. The idea of a container object is if for example your render loop wants the camera to look at the object already, and the object to rotate maybe, like viewing a product without reseting the rotation each time the product is changed. The meshes could be added/removed to this object instead.

1 Like

Ok thanks. I’ll give it a shot