Unity中glTFast的LoadGltfBinary加载GLTF文件失败问题及解决
Unity Android平台glTFast加载问题:LoadGltfBinary失败,Load方法成功
问题场景
在Unity 2022.1.7f1中使用glTFast 5.0.0包,Android平台加载GLTF文件时出现异常:通过LoadGltfBinary方法加载时,已确认读取到非空字节数组,但success始终返回false;改用Load方法后加载成功。
原失败代码
public async void SetModel(string path) { if (!File.Exists(path)) { Debug($"File does not exist: {path}"); } byte[] fileData; try { fileData = File.ReadAllBytes(path); } catch (IOException ex) { Debug($"Error reading file: {ex.Message}"); return ; } Debug(fileData.Length.ToString()); var gltf = new GltfImport(); bool success = await gltf.LoadGltfBinary( fileData, new System.Uri(path) ); if (success) { Debug("SUCCESS GLTF"); var mainScene = await gltf.InstantiateMainSceneAsync(ArPrefab.transform); } else { Debug("FAIL GLTF"); } }
修改后成功代码
public async void SetModel(string path) { if (!File.Exists(path)) { Debug($"File does not exist: {path}"); } var gltf = new GltfImport(); bool success = await gltf.Load(path); if (success) { Debug("SUCCESS GLTF"); try { GameObject root = new GameObject("test"); gltf.InstantiateMainScene(root.transform); } catch (Exception e) { Debug(e.ToString()); } } else { Debug("FAIL GLTF"); } }
可能的原因分析
- 文件类型匹配问题:
LoadGltfBinary方法设计用于加载GLB格式的二进制文件(单个文件包含所有资源),如果目标文件是标准GLTF(JSON+外部资源文件的组合),该方法无法处理外部依赖资源的加载,导致失败。而Load方法会自动检测文件类型,无论是GLTF还是GLB,都能正确解析并加载关联资源。 - 路径寻址差异:Android平台的文件系统路径处理有特殊性,手动读取字节数组后传入
LoadGltfBinary时,第二个参数的Uri可能无法正确定位外部资源的相对路径,导致资源加载失败;Load方法内部封装了更可靠的路径处理逻辑,能正确寻址关联资源。
内容的提问来源于stack exchange,提问作者Mark Alexander
相关产品推荐
相关产品推荐

