Swift-SceneKit无法从art.scnassets加载.scn文件求助
解决SCNScene无法加载本地.scn文件的问题
问题概述
无法加载ARDicee/art.scnassets文件夹下的diceCollada.scn及默认ship.scn文件,尝试两种SCNScene创建方式均失败。使用环境:Xcode 14.1,macOS Ventura 13.0.1。
尝试的代码
方式1:通过资源名加载
import UIKit import SceneKit import ARKit class ViewController: UIViewController, ARSCNViewDelegate { @IBOutlet var sceneView: ARSCNView! override func viewDidLoad() { super.viewDidLoad() sceneView.delegate = self sceneView.showsStatistics = true // 加载场景时触发错误 guard let diceScene = SCNScene(named: "art.scnassets/diceCollada.scn") else { fatalError() } if let diceNode = diceScene.rootNode.childNode(withName: "Dice", recursively: true) { diceNode.position = SCNVector3(x: 0, y: 0, z: -0.1) sceneView.scene.rootNode.addChildNode(diceNode) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if ARWorldTrackingConfiguration.isSupported { let configuration = ARWorldTrackingConfiguration() sceneView.session.run(configuration) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) sceneView.session.pause() } }
方式2:通过绝对路径加载
override func viewDidLoad() { super.viewDidLoad() sceneView.delegate = self sceneView.showsStatistics = true let filePath = URL(fileURLWithPath: "/Applications/xcode/Development/ARDicee/ARDicee/art.scnassets/diceCollada.scn") do { let diceScene = try SCNScene(url: filePath) if let diceNode = diceScene.rootNode.childNode(withName: "Dice", recursively: true) { diceNode.position = SCNVector3(x: 0, y: 0, z: -0.1) sceneView.scene.rootNode.addChildNode(diceNode) } } catch { print(error) } }
触发的错误信息
Error Domain=NSCocoaErrorDomain Code=260 "The file “diceCollada.scn” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Applications/xcode/Development/ARDicee/ARDicee/art.scnassets/diceCollada.scn, NSUnderlyingError=0x282924570 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
解决方案
1. 确认资源已加入编译Target
- 选中项目导航栏中的
art.scnassets文件夹,打开右侧File Inspector,检查Target Membership是否勾选当前项目的target。未勾选的文件不会被打包进App Bundle,导致加载失败。
2. 修正资源路径写法
- 绝对路径方式不可靠:App运行时无法直接访问本地磁盘的绝对路径,必须通过
Bundle获取资源路径:if let filePath = Bundle.main.path(forResource: "diceCollada", ofType: "scn", inDirectory: "art.scnassets") { let url = URL(fileURLWithPath: filePath) do { let diceScene = try SCNScene(url: url) // 节点操作逻辑 } catch { print(error) } } - 检查文件夹名称:确保项目内的文件夹是
art.scnassets(后缀为.scnassets,而非你提到的art.assets)。
3. 验证资源文件完整性
- 右键
art.scnassets选择Show in Finder,确认diceCollada.scn存在且未损坏;若文件缺失,重新导入并勾选Copy items if needed。
4. 清理缓存重新编译
- 按下
Command+Shift+K清理项目缓存,再按Command+B重新编译,避免缓存导致的路径匹配问题。
内容的提问来源于stack exchange,提问作者ADAM _YONEDA
相关产品推荐
相关产品推荐

