I've imported a 3D model into a THREE.Js project I've been working on, and I want to add several copies of them to the scene. Here's the code I've been using to duplicate it:
let ball = new THREE.Mesh();
loader.load( './ball.gltf', function ( gltf ) {
gltf.scene.traverse(function(model) { //for gltf shadows!
if (model.isMesh) {
model.castShadow = true;
model.material = sphereMaterial;
}
});
ball = gltf.scene;
scene.add( ball );
}, undefined, function ( error ) {
console.error( error );
} );
const ball2 = ball.clone()
ball2.position.set(0.5, 0.5, 0.5)
scene.add(ball2)
However, only one of the "balls" show up in the scene from the loader.load()
call. Does anyone happen to know what I should do differently to successfully duplicate the model?
Your onLoad()
handler (function ( gltf ) {...}
) is asynchronous, and the code that clones ball
(const ball2 = ball.clone()
) is executing before ball
is initialized with the GLTF data. So at the time ball.clone()
executes, ball
is simply the empty Mesh
you created before loading the GLTF, and that empty Mesh
is what gets cloned.
I suspect you were, at some point, getting a console error relating to reading clone
on undefined, and that's why you added the line to initialize ball
to an empty Mesh
, which is unnecessary.
There are a few ways to handle this, but the simplest is to move the code that clones ball
into the onLoad
handler (i.e., after scene.add( ball )
).
Proof of concept here.