@react-three / react-three-fiber: useLoader() 在 props 更改时加载新文件

Posted

技术标签:

【中文标题】@react-three / react-three-fiber: useLoader() 在 props 更改时加载新文件【英文标题】:@react-three / react-three-fiber: useLoader() to load new file on props change 【发布时间】:2021-07-13 05:19:52 【问题描述】:

我有一个功能性反应组件并初始加载一个 gltf 模型 - 路径通过道具 - 这工作正常。

但是如果道具改变了组件重新渲染 - 我检查了 - 路径改变了,应该加载一个新的模型 - 但我没有。

如何实现这一目标? 如果状态更新,我想交换/替换正在渲染的对象。

我尝试了不同的加载器,将 gltf 设置为一个状态,但这些都没有。我想我错过了一个基本概念。请帮忙

  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;
    

角色组件是这样渲染的:

<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>

【问题讨论】:

【参考方案1】:

我在渲染纹理时测试了useLoader 的问题,它对我来说效果很好。 这是一个简单的example,它显示纹理会随着props 的变化而变化。

我猜你错过了指向props.model 的正确路径。也许您可以硬编码props.model 的值,以确保文件路径正确与否。

已编辑

我找到了 gltf 只渲染一次的原因。答案是here。

您不能在 webgl/threejs 中重复使用网格或将同一对象两次放入场景中,它只会卸载和重新安装。

另一种解决方案是clone the scene。

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

我还在codesandbox上提供了一个固定示例。

【讨论】:

路径是正确的,我测试了它们并且也导入了,所以这不是问题。 我还修改了您的示例以使用 gltf 加载器,但这也不起作用。我什至不知道这是否可能,或者它是否与场景有关 @AlexanderFrey 你能分享你的例子吗? codesandbox.io/s/r3f-texture-url-forked-4looe?file=/src/App.js 我不得不重做它现在似乎以某种方式工作但不是 100%。可能是网络问题 但是我的还是不行我不知道怎么办

以上是关于@react-three / react-three-fiber: useLoader() 在 props 更改时加载新文件的主要内容,如果未能解决你的问题,请参考以下文章