How to add more models of the same kind into the scene using react three fiber?

How can I spawn new Models into my scene using react three fiber?

App = ()=>{

  return(
        {[...Array(5)].map((_, index) => (
          <Model key={index} />
        ))}
   )
}

what I tried is to have the array as a state variable using useState(); and increase it’s length if additional model is needed… but the new Model is not randered into the scene.

Model itself is something like this:

Model = ()=>{
  const ref = useRef();
  const {scene} = useGLTF("model.glb");
  useFrame(()=>{ ref.current.position.z +=0.1;})

  return <Clone object={scene} ref={ref} />
}

Does it work if you don’t use an array?

  1. Your code seems ok BUT
  2. You should wrap all your R3F code in a Canvas element (only one, at the top of R3F code, not one per model.)
  3. Make sure to first setup code with some simple mesh / boxGeometry / meshNormalMaterial first - then add loaders and models after all is setup nicely. Otherwise there’s just a bunch of things that can go wrong on the way, and you’ll spend all day debugging.

You can also go here for r3f questions: Poimandres

1 Like