How to add multiple gltf to scene using for loop

I’m using Three.js and React. I’m trying to display gltf object based on latitude and longitude in locations array of objects. I tried using for loop and access to each latitude and longitude and set position based on them, however only one gltf is show up on the screen. How do I add all the gltf to the scene?

My current code:

const locations = [
  { lat: 49.285804, lng: -123.119927 },
  { lat: 49.286704, lng: -123.129184 },
  { lat: 49.283365, lng: -123.100725 },
  { lat: 49.276688, lng: -123.126354 },
  { lat: 49.28101, lng: -123.11879 },
  { lat: 49.281228, lng: -123.125477 },
  { lat: 49.281603, lng: -123.110954 },
  { lat: 49.285806, lng: -123.137186 },
  { lat: 49.28407, lng: -123.113193 },
  { lat: 49.287405, lng: -123.125083 },
];

loader.load(
  "/low_australian_shepherd/scene.gltf",
  function (gltf) {
    for (let i = 0; i <= locations.length; i++) {
      gltf.scene.position.copy(
        overlay.latLngAltitudeToVector3({
          lat: locations[i].lat,
          lng: locations[i].lng,
        })
      );
      scene.add(gltf.scene);
    }
  },
);

You’re calling Scene.add on the same gltf object multiple times - so in the end it’ll be placed in the last of the positions. Clone the model after loading it to create multiple copies:

const clone = gltf.scene.clone();

clone.position.copy(newPosition);

scene.add(clone);
1 Like

Thank you!
So I updated my code. It seems that there are multiple gltf was added to scene however they are rendered so weird. I deleted objects except for one and made it only loop for one time, but still I see the same style of object. If I render just one gltf it looks different. It seems gltf.scene.clone(); part is affecting the shape of gltf. Do you come up with any reason?
Screenshot 2023-05-30 at 9.46.14 PM
Screenshot 2023-05-30 at 9.44.54 PM

    loader.load("/low_australian_shepherd/scene.gltf", function (gltf) {
      for (let i = 0; i <= locations.length; i++) {
        const clone = gltf.scene.clone();
        clone.scale.setScalar(2.5);
        clone.translateY(100);
        clone.rotateY(-90);
        clone.position.copy(
          overlay.latLngAltitudeToVector3({
            lat: locations[i].lat,
            lng: locations[i].lng,
          })
        );
        scene.add(clone);
      }
    });

I wrote like the following and it worked! Thank you so much.

import { clone } from "three/examples/jsm/utils/SkeletonUtils.js";

const locations = [
  { lat: 49.285804, lng: -123.119927 },
  { lat: 49.286704, lng: -123.129184 },
]

loader.load("/low_australian_shepherd/scene.gltf", function (gltf) {
  for (let i = 0; i <= locations.length; i++) {
    const cloneGLTF = clone(gltf.scene);
    scene.add(cloneGLTF);
  }
});