Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift RealityKit–;异步模型加载不';行不通_Swift_Asynchronous_Augmented Reality_Realitykit_Usdz - Fatal编程技术网

Swift RealityKit–;异步模型加载不';行不通

Swift RealityKit–;异步模型加载不';行不通,swift,asynchronous,augmented-reality,realitykit,usdz,Swift,Asynchronous,Augmented Reality,Realitykit,Usdz,此代码适用于: let entity = try! Entity.load(named: "toy_robot_vintage") anchorEntity.addChild(entity) 但这并不是: _ = Entity.loadAsync(named: "toy_robot_vintage") .sink(receiveCompletion: { loadCompletion in print("

此代码适用于:

let entity = try! Entity.load(named: "toy_robot_vintage")
anchorEntity.addChild(entity)
但这并不是:

_ = Entity.loadAsync(named: "toy_robot_vintage")
        .sink(receiveCompletion: { loadCompletion in
            print("This is never executed")
        }, receiveValue: { entity in
            print("This is never executed")
            anchorEntity.addChild(entity)
        })

可能出现什么问题?

使用以下macOS代码版本了解如何异步加载模型:

import AppKit
import RealityKit
import Combine

class GameViewController: NSViewController {
    
    @IBOutlet var arView: ARView!
    var model: ModelEntity? = nil
    let anchor = AnchorEntity()
    var cancellable: AnyCancellable? = nil
    
    override func awakeFromNib() {
    
        arView.environment.background = .color(.systemTeal)
                
        cancellable = Entity.loadModelAsync(named: "Glasses.usdz")
            .sink(receiveCompletion: { completion in
                if case let .failure(error) = completion {
                    print("Unable to load a model due to error \(error)")
                }
                self.cancellable?.cancel()
                
            }, receiveValue: { [self] (model: Entity) in
                if let model = model as? ModelEntity {
                    self.model = model
                    cancellable?.cancel()
                    print("Congrats! Model is successfully loaded!")
                    anchor.addChild(model)
                    anchor.position = [0.4, 1.5, -1]
                    anchor.scale = [300, 300, 300]        // set appropriate scale
                    arView.scene.anchors.append(anchor)
                }
            })
    }
}

这很有效。非常感谢你。显然,有必要在loadModelAsync()的闭包中取消从loadModelAsync()返回的AnyCancelable。这不是取消AnyCancelable,而是保存对LoadRequest的引用,这样ARC就不会因为引用计数为零而将其从内存中踢出。我还建议将anycancelable设置为弱,以避免循环引用(GameViewController->closure->anycancelable)