React Native渲染3D模型失败求助:OBJLoader加载报错
React Native + React Three Fiber: 3D模型加载失败(OBJ/GLTF)解决方案
问题诊断
你遇到的Error: Could not load 4: undefined报错,核心原因通常是Metro打包器未配置支持3D模型文件类型,或者模型加载方式不符合React Native的资源规则,也可能是模型文件本身存在损坏或依赖缺失。
解决步骤
1. 配置Metro打包器支持3D资源
React Native默认不会打包.obj/.gltf/.glb/.mtl这类文件,需要修改metro.config.js(项目根目录,没有则新建):
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config'); const config = { resolver: { assetExts: [...getDefaultConfig(__dirname).resolver.assetExts, 'obj', 'gltf', 'glb', 'mtl'], }, }; module.exports = mergeConfig(getDefaultConfig(__dirname), config);
修改后重启Metro服务,确保新配置生效。
2. 修正OBJ模型加载代码(含材质支持)
如果OBJ模型依赖MTL材质文件,必须先加载材质再加载模型,否则会触发加载失败。修改shoe.jsx:
import { useLoader } from '@react-three/fiber'; import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader'; import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader'; import { useMemo } from 'react'; const Shoe = (props) => { // 加载MTL材质文件(如果模型有材质依赖) const materials = useLoader(MTLLoader, require('../assets/threeD/shoe.mtl')); // 配置OBJLoader绑定材质 const objLoader = useMemo(() => { const loader = new OBJLoader(); materials.preload(); loader.setMaterials(materials); return loader; }, [materials]); // 加载OBJ模型 const obj = useLoader(objLoader, require('../assets/threeD/shoe.obj')); return <primitive object={obj} scale={10} {...props} />; }; export default Shoe;
若模型无材质依赖,可简化为直接加载OBJ,但需确保模型本身不引用外部资源。
3. GLTF/GLB模型加载示例
如果尝试GLTF模型,使用GLTFLoader的正确写法:
import { useLoader } from '@react-three/fiber'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; const GLTFModel = (props) => { const gltf = useLoader(GLTFLoader, require('../assets/threeD/model.glb')); // 渲染GLTF的场景对象 return <primitive object={gltf.scene} scale={0.5} {...props} />; }; export default GLTFModel;
4. 完善App.js的渲染逻辑
确保导入Suspense并添加基础灯光(否则模型可能因无光照而不可见):
import { Canvas } from '@react-three/fiber/native'; import { Suspense } from 'react'; import Shoe from './shoe'; export default function App() { return ( <Canvas camera={{ position: [0, 0, 5] }}> {/* 添加基础灯光 */} <ambientLight intensity={0.5} /> <pointLight position={[10, 10, 10]} /> {/* Suspense用于展示加载过渡状态 */} <Suspense fallback={<mesh><boxGeometry /><meshBasicMaterial color="gray" /></mesh>}> <Shoe position={[0, -1, 0]} /> </Suspense> </Canvas> ); }
可运行项目快速搭建
- 初始化项目:
npx react-native init RNThreeDemo cd RNThreeDemo
- 安装依赖:
npm install three @react-three/fiber @react-three/native
- 配置
metro.config.js(参考步骤1代码) - 将测试模型(如GLB格式)放入
assets/threeD目录 - 创建模型组件并修改App.js(参考步骤3、4)
- 运行项目:
npx react-native run-android # 或 run-ios
常见排查点
- 检查模型文件路径是否正确,
require的路径必须是静态字符串,不能使用变量 - 用Three.js编辑器打开模型,确认文件未损坏
- 大型模型建议压缩(如用glTF-Pipeline处理GLB文件),避免加载超时
- 确保重启Metro服务后再测试新配置
内容的提问来源于stack exchange,提问作者owdji
相关产品推荐
相关产品推荐

