Three Fiber (loading model)

Hello!

When you change the model(click on model), it reboots and goes black screen for half a second. How to make that switching models was smooth?

The black flicker can happen because the model is not yet fully downloaded from the internet and setup completely into memory by Threejs.

you need to preload all your models from the internet first,
add them all to the scene so that their geometry and textures are completely setup by Threejs into memory ready to go,
and then set the visibility of the models to false, for the ones that you don’t want to be visible yet.
And when everything is ready, you can display your scene.

Thanks for answer :crazy_face:
useEffect(() => {
// Preload next model
const nextIndex = (count + 1) % gallery.length
useGLTF.preload(gallery[nextIndex])
}, [count])

1 Like

or you could add this into your app.jsx

useGLTF.preload(gellery.map(({ url }) => url))

But you will need to probably put a Suspense somewhere to delay the presentation of the scene until all the models have finished downloading.

1 Like
<Suspense fallback={null}>
  <Model />
</Suspense>

suspense works like that, everything that suspends will make the whole boundary stop, which by default is the canvas itself. if you wrap stuff that loads, then only that will pause, everything else is left standing.

you can also hold on to the current models while loading the new, look into the useTransition hook from react.

preloading in useEffect will not get you any benefits, it maybe saves you a clock tick because next frame the component will load anyway. you would normally preload in global space, before even the UI is up, this allows it to already fetch and parse the models and by the time the components render they’re either waiting for the result to finish or use the already finished result.

dont have suspense only tag (canvas)

suspense is a react feature. useGLTF suspends. and you control the loading process with the suspense component. this will immediately fix your problem. also read through what i wrote up there again, you can hold on to models while loading, if you wanted that.

import { Suspense } from 'react'

its three fiber ,he does it himself under the hood

another thing that’s wrong:

  const { scene } = useGLTF(gallery[count])
  return (
    <group>
      {scene && (
        <primitive

it’s just this:

  const { scene } = useGLTF(gallery[count])
  return <primitive ...

scene is guaranteed to be present, it cannot possibly be undefined.

i do not understand. use suspense. react-three-fiber is react, it is based on suspense, all loader hooks are.

here’s a fixed sandbox React Three Fiber Boilerplate - useGLTF (forked) - CodeSandbox

1 Like

interesting solution