4

I have a functional react component and initial load a gltf model - the path gets passed through the props - this works fine.

But if the props change the component rerenders - I checked that - the path is changed and a new Model should be loaded - but I does not.

How can one achieve this? I want to swap/replace the object that is rendering if the state is updated.

I tried different loaders, set the gltf it self as a state but none of this wokred. I think I miss an underlying concept. Pls Help

  function Character(props) {
      const spinner = useRef();
      console.log(props.model, "from modelpreviewer");
      const gltf = useLoader(GLTFLoader, props.model);
    
      return gltf ? (
        <primitive
          ref={spinner}
          object={gltf.scene}
        />
      ) : null;
    }

The Character Component is rendered like this:

<Canvas
   camera={{ position: [0, 0, 10] }}>
    <ambientLight intensity={0.8} />
    <spotLight intensity={0.7} position={[300, 300, 400]} />
    <Suspense fallback={null}>
      <Character model={props.model} />
    </Suspense>
  </Canvas>
Alex
  • 111
  • 2
  • 9

1 Answers1

3

I test the problem of useLoader when render the texture and it works fine to me. This a simple example which shows the texture will change whenever the props changed.

I guess you're miss the correct path point to props.model. Maybe you can hard code a value of props.model to make sure the file path is correct or not.

Edited

I find the reason why gltf just render once. The answer is here.

You can't reuse meshes or put the same object into the scene twice in webgl/threejs, it will just unmount and remount.

An alternatively solution is to clone the scene.

const { scene } = useLoader(GLTFLoader, url)
const copiedScene = useMemo(() => scene.clone(), [scene])

I also provide a fixed example on codesandbox.

bcjohn
  • 2,383
  • 12
  • 27
  • the path are right i tested them and there are also imported so that is not the issue. – Alex Apr 19 '21 at 04:05
  • i also modified your example to use the gltf loader and that did not work either. I dont know if it is even possible or if it has something to do with the scene – Alex Apr 19 '21 at 04:28
  • @AlexanderFrey Could you share your example? – bcjohn Apr 19 '21 at 05:42
  • https://codesandbox.io/s/r3f-texture-url-forked-4looe?file=/src/App.js i had to redo it it seems to worke now somehow but not 100%. maybe thats an network isue – Alex Apr 19 '21 at 12:18
  • but mine still wont work i dont know what to do – Alex Apr 19 '21 at 12:18
  • thank youu so much. i tried so many things an thought about something like this but could not get is to work! :) – Alex Apr 19 '21 at 13:04
  • 1
    dude this is such a big help in 2022. this totally solved my problems. thanks! – Lee Merlas Apr 22 '22 at 19:56