'RealityKit – Get a model entity from USDZ file
I haave a file (exists in main bundle with target membership checked) named matrix.usdz
and need to load it with
do {
let path = Bundle.main.path(forResource: "Matrix", ofType: "usdz")!
let url = URL(fileURLWithPath: path)
let assetsLoader = try Entity.load(contentsOf: url)
}
catch {
print(error)
}
But it crashes with
Thread 1: signal SIGABRT
on this line
let assetsLoader = try Entity.load(contentsOf: url)
Preview
Solution 1:[1]
You have to create an anchor if you need to load an entity into your scene. In order to get a ModelEntity, you need to grab it from the scene hierarchy using .children[X]
subscript.
import RealityKit
class ViewController: UIViewController {
@IBOutlet var arView: ARView!
override func viewDidLoad() {
super.viewDidLoad()
do {
let path = Bundle.main.path(forResource: "Matrix", ofType: "usdz")!
let url = URL(fileURLWithPath: path)
// Scene
let scene = try Entity.load(contentsOf: url)
print(scene)
// Entity
let entity = scene.children[0].........children[0] as! ModelEntity
entity.model?.materials[0] = UnlitMaterial(color: .red)
let anchor = AnchorEntity(plane: .any)
anchor.addChild(scene)
arView.scene.anchors.append(anchor)
} catch {
print(error)
}
}
}
You can also get a model this way:
let modelEntity = try Entity.loadModel(contentsOf: url)
modelEntity.model?.materials[0] = UnlitMaterial(color: .red)
P.S.
I should say that you have an obvious naming error – "Matrix" vs "matrix". Also Matrix.rcproject
and Matrix.usdz
are not the same. To load Matrix.rcproject
(Reality Composer project) use the following approach:
// .rcproject
let scene = try! Matrix.loadCircle()
let circleEntity = scene.children[0]...........children[0] as! ModelEntity
to load a USDZ model use this one:
// .usdz
let model = try! Entity.loadModel(named: "Matrix", in: nil)
But as far as I know, you do not need an RC project, so export USDZ from Reality Composer.
To load .reality
file use the following approach:
// .reality
let carModel = try! Entity.loadAnchor(named: "car")
print(carModel)
arView.scene.addAnchor(carModel)
Here's your USDZ model on iOS simulator:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |