iOS 18中ModelEntity.loadAsync已废弃,寻求代码修改方案
iOS 18中ModelEntity.loadAsync已废弃,寻求代码修改方案
嗨,我刚好在适配iOS 18的RealityKit代码时遇到过一模一样的问题!Apple在iOS 18里把ModelEntity.loadAsync(named:)标记为废弃了,现在官方推荐使用更通用的Entity.loadAsync(named:in:)方法来替代它。
下面是修改后的完整代码,我会把关键的修改点给你标出来:
import ARKit import RealityKit import Combine class Coordinator: NSObject, ARSessionDelegate { weak var view: ARView? var cancellable: AnyCancellable? @objc func handleTap(_ recognizer: UITapGestureRecognizer) { guard let view = self.view else { return } let tapLocation = recognizer.location(in: view) let results = view.raycast(from: tapLocation, allowing: .estimatedPlane, alignment: .horizontal) if let result = results.first { // create anchor entity let anchor = AnchorEntity(raycastResult: result) // 替换废弃的ModelEntity.loadAsync为Entity.loadAsync cancellable = Entity.loadAsync(named: "shoe") .sink { loadCompletion in if case let .failure(error) = loadCompletion { print("Unable to load model \(error)") } self.cancellable?.cancel() } receiveValue: { entity in // 安全将通用Entity转型为ModelEntity guard let modelEntity = entity as? ModelEntity else { print("Loaded entity is not a ModelEntity") return } anchor.addChild(modelEntity) } view.scene.addAnchor(anchor) } } }
我再给你拆解下关键的修改点:
- 替换废弃API:把原来的
ModelEntity.loadAsync(named: "shoe")换成Entity.loadAsync(named: "shoe"),这是iOS 18里RealityKit推荐的通用模型加载方法 - 安全转型处理:因为
Entity.loadAsync返回的是通用的Entity类型,所以我们需要用as? ModelEntity做安全转型,同时加上转型失败的日志处理,避免潜在的崩溃 - 保持原有逻辑:除了API替换和转型,其他的取消订阅、添加锚点等逻辑都和你原来的代码保持一致,不会影响你原本的功能
这样修改后,代码就能在iOS 18上正常运行,同时也能兼容较低版本的iOS系统(只要你在项目里做好版本适配的话)。
备注:内容来源于stack exchange,提问作者john doe
相关产品推荐
相关产品推荐

