Load models in multi scenes

Referring previous task: Parent post

I need to create a viewer of many items and I would like to import models in a grid. I created a single canvas and then for each item I created a scene having an object and a div mask to show it.

It works well.

Now I have added a model into every single scene but I’m getting in trouble. If I do:

models.forEach(function(e){
     scene = new THREE.Scene();
     ....
 // loader
       loader.load(
           '/three-assets/'+e.model,
           gltf => {
             scene.add(gltf.scene);

           },
           undefined,
           undefined
       )
     scenes.push(scene);
})

I have all the models in the last scene.
If I move the scenes.push(scene); inside the loader function, just after adding the gltf.scene to the current scene, I lost everything other objects.

I guess it is an async and namespace issue. How can I fix it?

I created a: jsFiddle but I’m not able to load the model to show my issue.

Thanks for your help

I think it’s just a scope issue. It looks like you have a variable scene in higher scope. For each model you call scene = new THREE.Scene();, which assign a new THREE.Scene to the variable scene. After, when the models load, they are added to scene, which is the last of the THREE.Scene you created.

Try declaring a variable scene in function scope :

models.forEach(function(e){
     const scene = new THREE.Scene();
     ....
 // loader
       loader.load(
           '/three-assets/'+e.model,
           gltf => {
             scene.add(gltf.scene);

           },
           undefined,
           undefined
       )
     scenes.push(scene);
})

Yes! It makes sense!! Fresh eyes always help!! Thanks man :smiley:

1 Like