如何为 TextureResource 使用 loadAsync

How to use loadAsync for TextureResource

我在为 TextResource 使用 loadAsync 时遇到问题 class。它 returns LoadRequest<TextureResource> 但我也不知道该如何处理。这些对象的文档很差,我也找不到任何教程。任何人都可以解决它吗?谢谢!

let url = URL(fileURLWithPath: imageFilePath)
let texture = try! TextureResource.loadAsync(contentsOf: url).result!.get()
var material = SimpleMaterial()
material.baseColor = MaterialColorParameter.texture(texture)
let entity = ModelEntity(mesh: paintingMesh, materials: [material])

好的,我解决了这个问题,我想分享答案! 所以基本上我们必须使用 Combine 框架来处理异步请求 有代码示例,记得add import Combine

        var textureRequest: AnyCancellable? = nil
        textureRequest = TextureResource.loadAsync(contentsOf: url).sink { (error) in
            print(error)
            textureRequest?.cancel()
        } receiveValue: { (texture) in
            var material = UnlitMaterial()
            material.baseColor = MaterialColorParameter.texture(texture)        
            // Do another setup
            textureRequest?.cancel()
        }

重要的是我们必须取消请求,取消它。 您可以在 Apple 文档中找到更多信息 https://developer.apple.com/documentation/combine/receiving-and-handling-events-with-combine 或者那里 https://medium.com/@ethansaadia/realitykit-assets-52ada3f9465f